Search code examples
pythonpytz

Incorrectly converting between Eastern and GMT time


I am having a strange issue in converting the following time from eastern to UTC/GMT. Can someone advise?

>>> import datetime
>>> import pytz
>>> 
>>> ept_time = datetime.datetime(2014,03,21,7)  # March 21st at 7am
>>> ept_time = ept_time.replace(tzinfo=pytz.timezone('US/Eastern'))
>>> print ept_time
2014-03-21 07:00:00-05:00
>>> 
>>> gmt_time = pytz.utc.normalize(ept_time)
>>> print gmt_time
2014-03-21 12:00:00+00:00
>>> 

However, according to Wolfram Alpha, the results should be 11am, not 12.


Solution

  • >>> gmt = pytz.timezone('GMT')
    >>> eastern = pytz.timezone('US/Eastern')
    >>> d = datetime.datetime(2014,03,21,7)
    >>> dateeastern = eastern.localize(d)
    >>> dateeastern
    datetime.datetime(2014, 3, 21, 7, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
    >>> dategmt = dateeastern.astimezone(gmt)
    >>> dategmt
    datetime.datetime(2014, 3, 21, 11, 0, tzinfo=<StaticTzInfo 'GMT'>)
    

    Replace GMT with UTC:

    >>> eastern = pytz.timezone('US/Eastern')
    >>> d = datetime.datetime(2014,03,21,7)
    >>> dateeastern = eastern.localize(d)
    >>> dateeastern
    datetime.datetime(2014, 3, 21, 7, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
    >>> dateutc = dateeastern.astimezone(pytz.utc)
    >>> dateutc
    datetime.datetime(2014, 3, 21, 11, 0, tzinfo=<UTC>)
    

    Ref: How to convert GMT time to EST time using python