我想将 GMT 时间转换为 EST 时间并获得时间戳。我尝试了以下但不知道如何设置时区。
time = "Tue, 12 Jun 2012 14:03:10 GMT"
timestamp2 = time.mktime(time.strptime(time, '%a, %d %b %Y %H:%M:%S GMT'))
时区没有内置在标准 Python 中——您需要使用另一个库。pytz是一个不错的选择。
>>> 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>)
使用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)
在Python 3.9中,时区处理通过zoneinfo模块内置到标准库中(对于较旧的 Python 版本,zoneinfo
通过backports.zoneinfo使用)。
前任:
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
还有dateutil
,它遵循相同的语义:
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
如果它是您的本地时区,并且给定时间的时区规则与现在相同,那么您可以使用仅限 stdlib 的解决方案(某些边缘情况除外):
#!/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
否则,您需要来自历史时区数据库的数据才能获得正确的 UTC 偏移量。pytz
模块提供对 tz 数据库的访问:
#!/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)
注意:POSIXtimestamp
在世界各地都是一样的,即,如果您想查找时间戳,您的本地时区并不重要(除非您的时区是“正确的”类型)。以下是将 UTC 时间转换为时间戳的方法。