Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a timestamp string with timezone offset to local time?

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 = "Fri, 16 Jul 2010 07:08:23 -0700"
like image 964
alfredo Avatar asked Jul 20 '10 03:07

alfredo


2 Answers

The dateutil package is handy for parsing date/times:

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 into your local timezone,

In [13]: parse(date).astimezone(YOUR_LOCAL_TIMEZONE)
like image 58
ars Avatar answered Sep 17 '22 00:09

ars


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:

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)
like image 41
Chris B. Avatar answered Sep 20 '22 00:09

Chris B.