0

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.

jsexauer
  • 681
  • 2
  • 12
  • 22
  • 1
    your eastern time isn't converting properly. we're in daylight saving time, so it should be `-04:00` at the end. maybe something like this would help: `>>> before = loc_dt - timedelta(minutes=10) >>> before.strftime(fmt) '2002-10-27 00:50:00 EST-0500' >>> eastern.normalize(before).strftime(fmt) '2002-10-27 01:50:00 EDT-0400' >>> after = eastern.normalize(before + timedelta(minutes=20)) >>> after.strftime(fmt) '2002-10-27 01:10:00 EST-0500'` – acushner Mar 25 '14 at 15:04
  • possible duplicate of [How to convert GMT time to EST time using python](http://stackoverflow.com/questions/10999021/how-to-convert-gmt-time-to-est-time-using-python) – 2rs2ts Mar 25 '14 at 15:29
  • @2rs2ts: it is the opposite direction. EST -> GMT, not GMT -> EST. – jfs Sep 04 '14 at 10:37

1 Answers1

4
>>> 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

Community
  • 1
  • 1
Chien-Wei Huang
  • 1,773
  • 1
  • 17
  • 27
  • Thanks. How is `localize` different than using the `replace()` method of a datetime? – jsexauer Mar 25 '14 at 15:31
  • to assert that the input time is unambiguous, pass `is_dst=None` to `.localize()`. In general, pytz docs recommend `.normalize()`: `dategmt = gmt.normalize(dateeastern.astimezone(gmt))` (though it probably unnecessary in this case). – jfs Mar 25 '14 at 18:31
  • @jsexauer: the fist `note:` in [pytz docs](http://pytz.sourceforge.net/) recommends `.localize()`. In short, the same timezone may have different utc offsets in the past (unrelated to DST transitions) and `.replace()` may pick the wrong offset – jfs Mar 25 '14 at 18:33
  • use `pytz.utc` instead of `pytz.timezone('GMT')`. – jfs Mar 25 '14 at 18:39