我希望将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'))
答案 0 :(得分:23)
时区未内置于标准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>)
答案 1 :(得分:3)
使用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)
答案 2 :(得分:3)
在 Python 3.9 中,时区处理功能是通过zoneinfo模块内置到标准库中的(对于较早的Python版本,请通过backports.zoneinfo使用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
答案 3 :(得分:0)
如果是您的本地时区,并且时区规则在给定时间内与现在相同,那么您可以使用仅限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
module可以访问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)
注意:POSIX timestamp
在全球范围内是相同的,即如果您想要找到时间戳,则您的本地时区无关紧要(除非您的时区属于“正确”类型)。以下是convert a utc time to the timestamp的方法。