Search code examples
pythonpython-2.7pytz

How are you supposed to know which pyTZ is actually going to do as expected?


So the following code in the shell illustrates the problem pretty well. As I'm writing this, it is about 17:32 at (hence the 5:32) But what does not make sense is why?

 >>> d = datetime.datetime(2015,3,15,13,0,0,tzinfo=pytz.timezone('America/Detroit'))
 >>> d.isoformat()
 '2015-03-15T13:00:00-05:32'

 >>> d = datetime.datetime(2015,3,15,13,0,0,tzinfo=pytz.timezone('US/Eastern'))
 >>> d.isoformat()
 '2015-03-15T13:00:00-04:56'

And finally this works, but I don't understand why.

 >>> d = datetime.datetime(2015,3,15,13,0,0,tzinfo=pytz.timezone('EST'))
 >>> d.isoformat()
 '2015-03-15T13:00:00-05:00'

How are you supposed to know which TZ is actually going to do as expected?


Solution

  • You can't create a datetime by passing a value to tzinfo=. In your case the correct approach is to create a naive datetime and localize it:

    >>> d = datetime.datetime(2015,3,15,13,0,0)
    >>> pytz.timezone('EST').localize(d).isoformat()
    '2015-03-15T13:00:00-05:00'
    

    Similarly:

    >>> pytz.timezone('US/Eastern').localize(d).isoformat()
    '2015-03-15T13:00:00-04:00'
    >>> pytz.timezone('America/Detroit').localize(d).isoformat()
    '2015-03-15T13:00:00-04:00'