Handling timezones is always a bit confusing. In your example, you were not specific in your needs as it relates to the timezone.
Fixed timezone offset:
One way to read what you wrote is that the timezone information in your string is always GMT-00:00
. If the timezone is always the same, then it is a simple matter to build a strptime
string as:
dt.datetime.strptime(date, '%a %b %d %H:%M:%S GMT-00:00 %Y')
This makes no effort to interpret the timezone, since it is fixed. This will give you timezone naive datetime
. And since your example immediately converted the datetime
to a timetuple
, I assume this is the result you wanted.
To test:
>>> date = "Sat Apr 14 21:05:23 GMT-00:00 2018"
>>> print(dt.datetime.strptime(date, '%a %b %d %H:%M:%S GMT-00:00 %Y'))
2018-04-14 21:05:23
Interpreting the timezone offset:
If you have non-GMT timezones in your timestamps, and want to preserve the information you can do:
def convert_to_datetime(datetime_string):
# split on spaces
ts = datetime_string.split()
# remove the timezone
tz = ts.pop(4)
# parse the timezone to minutes and seconds
tz_offset = int(tz[-6] + str(int(tz[-5:-3]) * 60 + int(tz[-2:])))
# return a datetime that is offset
return dt.datetime.strptime(' '.join(ts), '%a %b %d %H:%M:%S %Y') - \
dt.timedelta(minutes=tz_offset)
This function will take your time string and make use of the UTC
offset. (eg. -00:00
). It will parse the timezone information out of the string and then add the resulting minutes and seconds back into the datetime
to make it UTC
relative.
To test:
>>> print(convert_to_datetime("Sat Apr 14 21:05:23 GMT-00:00 2018"))
2018-04-14 21:05:23
>>> print(convert_to_datetime("Sat Apr 14 21:05:23 PST-08:00 2018"))
2018-04-15 05:05:23
Timezone aware:
The above codes return a UTC
relative timezone naive datetime
. It if you need a timezone aware datetime
, then you can do that with:
datetime.replace(tzinfo=pytz.UTC))
To test:
>>> import pytz
>>> print(convert_to_datetime("Sat Apr 14 21:05:23 GMT-00:00 2018").replace(tzinfo=pytz.UTC))
2018-04-14 21:05:23+00:00