Convert timestamp of a string (clockwise offset) to local time.,? python

I am trying to convert the timestamp of a string to the corresponding datetime object. The problem I am facing is that there is a clockwise offset, and everything I do seems to not work.

Ultimately, I want to convert the timestamp of a string to a datetime object in the time zone of machines.

# string timestamp date = u"Fri, 16 Jul 2010 07:08:23 -0700" 
+7
python timezone datetime
source share
3 answers

Dateutil package is convenient for parsing date / time:

 In [10]: date = u"Fri, 16 Jul 2010 07:08:23 -0700" In [11]: from dateutil.parser import parse In [12]: parse(date) Out[12]: datetime.datetime(2010, 7, 16, 7, 8, 23, tzinfo=tzoffset(None, -25200)) 

Finally, to convert to your time zone,

 In [13]: parse(date).astimezone(YOUR_LOCAL_TIMEZONE) 
+8
source share

It looks like datetime.datetime.strptime(d, '%a, %d %b %Y %H:%M:%S %z') should work, but according to this error report there are problems processing %z . Therefore, you probably have to process the time zone yourself:

 import datetime d = u"Fri, 16 Jul 2010 07:08:23 -0700" d, tz_info = d[:-5], d[-5:] neg, hours, minutes = tz_info[0], int(tz_info[1:3]), int(tz_info[3:]) if neg == '-': hours, minutes = hours * -1, minutes * -1 d = datetime.datetime.strptime(d, '%a, %d %b %Y %H:%M:%S ') print d print d + datetime.timedelta(hours = hours, minutes = minutes) 
+4
source share

Here's the stdlib solution:

 >>> from datetime import datetime >>> from email.utils import mktime_tz, parsedate_tz >>> datetime.fromtimestamp(mktime_tz(parsedate_tz(u"Fri, 16 Jul 2010 07:08:23 -0700"))) datetime.datetime(2010, 7, 16, 16, 8, 23) # your local time may be different 

See also Python: parsing dates with timezone from email .

Note. fromtimestamp() can fail if in the past (2010) the local time zone had a different UTC offset and if it does not use the historical time database on this platform. To fix this, you can use tzlocal.get_localzone() to get the pytz tzinfo object representing your timezone. pytz provides access to the tz database in a portable way:

 >>> timestamp = mktime_tz(parsedate_tz(u"Fri, 16 Jul 2010 07:08:23 -0700")) >>> import tzlocal # $ pip install tzlocal >>> str(datetime.fromtimestamp(timestamp, tzlocal.get_localzone())) '2010-07-16 16:08:23+02:00' 
0
source share

All Articles