I am trying to convert a string timestamp into a proper datetime object. The problem I am having is that there is a timezone offset and everything I am doing doesn't seem to work.
Ultimately I want to convert the string timestamp into a datetime object in my machines timezone.
# string timestamp
date = u"Fri, 16 Jul 2010 07:08:23 -0700"
The dateutil package is handy for parsing date/times:
Finally, to convert into your local timezone,
It looks like
datetime.datetime.strptime(d, '%a, %d %b %Y %H:%M:%S %z')
should work, but according to this bug report there are issues with the%z
processing. So you'll probably have to handle the timezone on your own:Here's a stdlib solution:
See also, Python: parsing date with timezone from an email.
Note:
fromtimestamp()
may fail if the local timezone had different UTC offset in the past (2010) and if it does not use a historical timezone database on the given platform. To fix it, you could usetzlocal.get_localzone()
, to get apytz
tzinfo object representing your local timezone.pytz
provides access to the tz database in a portable manner: