pythontimeenviron

Can't figure out TZ issue in python


I don't understand how python is calculating time. Seems inconsistent to me.

My server time is:

admin@httstools ~ $ date
Fri Dec 21 17:00:51 PST 2018

In python interpreter I get the expected result (ie 2018-12-21):

admin@httstools ~ $ python
Python 2.7.5 (default, Nov  6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> import datetime
>>> str(datetime.date.today())
'2018-12-21'
>>>

But if I mess with timezone, things get screwy:

>>> time.tzname[time.localtime().tm_isdst]
'PST'

PST is the correct timezone. But if I set my environment to that TZ, and then run the previous command again, I get a different date, which obvious is not correct:

>>> os.environ['TZ'] = time.tzname[time.localtime().tm_isdst]
>>> str(datetime.date.today())
'2018-12-22'
>>>

The expected result would be 2018-12-21 with the TZ variable set to "PST".

As a followup, what command can I run in python that will always return the correct date/time based on my location.


Solution

  • Here's my guess as to what's happening (I don't have a Linux system to test on at the moment).

    If you examine the TZ environment variable, you'll see that it should really be of the syntax "America/Pacific" not "PST" (PST is simply an abbreviation that gets used for printing purposes). When an invalid value is passed through the TZ environment variable, I'm guessing Python falls back to UTC as a sane default.

    The UTC time for 5:00 PM PST just happens to be midnight the next day, which is why you get a different date.