How to convert GMT time to EST time using python
Time zones aren't built into standard Python - you need to use another library. pytz is a good choice.
>>> gmt = pytz.timezone('GMT')
>>> eastern = pytz.timezone('US/Eastern')
>>> time = "Tue, 12 Jun 2012 14:03:10 GMT"
>>> date = datetime.datetime.strptime(time, '%a, %d %b %Y %H:%M:%S GMT')
>>> date
datetime.datetime(2012, 6, 12, 14, 3, 10)
>>> dategmt = gmt.localize(date)
>>> dategmt
datetime.datetime(2012, 6, 12, 14, 3, 10, tzinfo=<StaticTzInfo 'GMT'>)
>>> dateeastern = dategmt.astimezone(eastern)
>>> dateeastern
datetime.datetime(2012, 6, 12, 10, 3, 10, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
Using pytz
from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
now_time = datetime.now(timezone('US/Eastern'))
print now_time.strftime(fmt)
With Python 3.9, time zone handling is built into the standard lib with the zoneinfo module (for older Python versions, use zoneinfo
via backports.zoneinfo).
Ex:
from zoneinfo import ZoneInfo
from datetime import datetime, timezone
time = "Tue, 12 Jun 2012 14:03:10 GMT"
# parse to datetime, using %Z for the time zone abbreviation
dtobj = datetime.strptime(time, '%a, %d %b %Y %H:%M:%S %Z')
# note that "GMT" (=UTC) is ignored:
# datetime.datetime(2012, 6, 12, 14, 3, 10)
# ...so let's correct that:
dtobj = dtobj.replace(tzinfo=timezone.utc)
# datetime.datetime(2012, 6, 12, 14, 3, 10, tzinfo=datetime.timezone.utc)
# convert to US/Eastern (EST or EDT, depending on time of the year)
dtobj = dtobj.astimezone(ZoneInfo('US/Eastern'))
# datetime.datetime(2012, 6, 12, 10, 3, 10, tzinfo=zoneinfo.ZoneInfo(key='US/Eastern'))
print(dtobj)
# 2012-06-12 10:03:10-04:00
And there's also dateutil
, which follows the same semantics:
import dateutil
# no strptime needed...
# correctly localizes to GMT (=UTC) directly
dtobj = dateutil.parser.parse(time)
dtobj = dtobj.astimezone(dateutil.tz.gettz('US/Eastern'))
# datetime.datetime(2012, 6, 12, 10, 3, 10, tzinfo=tzfile('US/Eastern'))
print(dtobj)
# 2012-06-12 10:03:10-04:00