2

我的计算机在太平洋时间运行(因此 datetime.datetime.fromtimestamp(0) 给我 1969-12-31 16:00:00)。我的问题是,给定 Python 中的时区感知 datetime 对象,我想获取 UNIX 时间戳(即 UTC 时间戳)。最好的方法是什么?

4

1 回答 1

8
import calendar
import datetime
import pytz

d = datetime.datetime.now(pytz.timezone('America/Los_Angeles'))
# d == datetime.datetime(2012, 7, 10, 1, 6, 36, 37542, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)

ts = calendar.timegm(d.utctimetuple())
# ts == 1341907596

# test with UTC epoch:

d = datetime.datetime(1969, 12, 31, 16, 0, 0, 0, pytz.timezone('America/Los_Angeles'))
# d == datetime.datetime(1969, 12, 31, 16, 0, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

ts = calendar.timegm(d.utctimetuple())
# ts == 0
于 2012-07-10T08:05:36.643 回答