Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python timezone offset wrong? [duplicate]

I'm writing a python script which contains two lines of code converting the date that got passed into the method to UTC time:

print "Timezone: %s" % get_localzone()
date = datetime.now(tz=get_localzone())
print "Local time: %s" % date
utc = pytz.utc
utc_date = date.astimezone(utc)
print "UTC date: %s" % utc_date

and the result is:

Timezone: America/Chicago
Local time: 2015-06-17 14:58:45.224827-05:00
UTC date: 2015-06-17 19:58:45.224827+00:00

As you can see the offset in local time is "-05:00", nothing wrong with it, but when I create a customized datetime object with the same timezone:

date = datetime(2015, 6, 17, 14, 58, 45, tzinfo=get_localzone())

The result becomes:

Timezone: America/Chicago
Local time: 2015-06-17 14:58:45-05:51

The offset changed from "-05:00" to "-05:51". I even used the same time that the first "datetime.now()" generated, and the timezone did not change, would someone please explain to me why is this happening? Thanks!

like image 399
YueQi Li Avatar asked Jun 17 '15 20:06

YueQi Li


1 Answers

Instead of assigning the tzinfo parameter, use the localize method from pytz.

tz = get_localzone()
date = tz.localize(datetime(2015, 6, 17, 14, 58, 45))

This is discussed prominently in the pytz documentation, starting with the the first "Note" box, and in the very first code sample.

It's also shown in the tzlocal documentation, which is where (I assume) your get_localzone() method is coming from.

FYI, the -05:51 offset comes from the original LMT value of the America/Chicago time zone, which is -05:50:36 and is assumed to have been in use way back in 1883 as shown here. It's rounded to the nearest minute, giving the -05:51 LMT value in Python. You are seeing that offset because the localize method wasn't called, so pytz is just using the first offset known to that time zone's entry.

like image 173
Matt Johnson-Pint Avatar answered Nov 18 '22 16:11

Matt Johnson-Pint