How to convert GMT time to EST time using python

2019-03-13 05:21发布

I want convert GMT time to EST time and get a timestamp. I tried the following but don't know how to set timezone.

time = "Tue, 12 Jun 2012 14:03:10 GMT"
timestamp2 = time.mktime(time.strptime(time, '%a, %d %b %Y %H:%M:%S GMT'))

3条回答
迷人小祖宗
2楼-- · 2019-03-13 05:37

If it is your local timezone and the timezone rules are the same for the given time as they are now then you could use stdlib-only solution (except for some edge cases):

#!/usr/bin/env python
from email.utils import parsedate_tz, mktime_tz
from datetime import datetime

timestamp = mktime_tz(parsedate_tz("Tue, 12 Jun 2012 14:03:10 GMT"))
print(datetime.fromtimestamp(timestamp))
# -> 2012-06-12 10:03:10

Otherwise you need data from a historical timezone database to get the correct utc offset. pytz module provides access to the tz database:

#!/usr/bin/env python
from email.utils import parsedate_tz, mktime_tz
from datetime import datetime
import pytz # $ pip install pytz

timestamp = mktime_tz(parsedate_tz("Tue, 12 Jun 2012 14:03:10 GMT"))
eastern_dt = datetime.fromtimestamp(timestamp, pytz.timezone('America/New_York'))
print(eastern_dt.strftime('%a, %d %b %Y %H:%M:%S %z (%Z)'))
# -> Tue, 12 Jun 2012 10:03:10 -0400 (EDT)

Note: POSIX timestamp is the same around the world i.e., your local timezone doesn't matter if you want to find the timestamp (unless your timezone is of "right" kind). Here's how to convert a utc time to the timestamp.

查看更多
仙女界的扛把子
3楼-- · 2019-03-13 05:45

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)
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-03-13 05:51

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>)
查看更多
登录 后发表回答