pythonparsingdatetimetimezoneiron.io

dateutil.parser handling of datestring ending in Z


I have datestrings that look like this: '2015-03-02T10:00:00Z'. On my local machine, dateutil.parser.parse() yields datetime objects with timezone UTC, as I would expect. But in a different environment (when I deploy to iron.io), it parses the same strings and gives the resulting datetimes tzlocal() as their tzinfo.

Is there a known reason that should ever happen? Why would environment affect how that Z is parsed?

(both environments should be Python 2.7)


Solution

  • I see that this question is old, but I was just having a similar issue. In my case, I discovered that, for some reason, if the current time zone is UTC, when I parse a string like "2017-02-23T06:54:00Z", the resulting datetime has tzinfo=tzlocal(); while for other timezones the resulting datetime has tzinfo=tzutc() as expected.

    In [1]: import time, os
    
    In [2]: from dateutil import parser
    
    In [3]: time.tzname, time.timezone
    Out[3]: (('EST', 'EDT'), 18000)
    
    In [4]: parser.parse("2017-02-23T06:54:00Z")
    Out[4]: datetime.datetime(2017, 2, 23, 6, 54, tzinfo=tzutc())
    
    In [5]: os.environ['TZ'] = 'UTC'
    
    In [6]: time.tzset()
    
    In [7]: time.tzname, time.timezone
    Out[7]: (('UTC', 'UTC'), 0)
    
    In [8]: parser.parse("2017-02-23T06:54:00Z")
    Out[8]: datetime.datetime(2017, 2, 23, 6, 54, tzinfo=tzlocal())