如果d = date(2011, 1, 1) 是UTC:
>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)
如果d 在本地时区:
>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)
如果本地时区的午夜与 UTC 的午夜不是同一时间实例,timestamp1 和 timestamp2 可能会有所不同。
如果d 对应于ambiguous local time (e.g., during DST transition) 或者如果d 是过去(未来)日期,此时UTC 偏移量可能不同并且
mktime() 可能返回错误结果C mktime() 在给定平台上无权访问 the tz database。你可以use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms。另外,utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used。
在没有calendar.timegm()的情况下转换代表UTC日期的datetime.date对象:
DAY = 24*60*60 # POSIX day in seconds (exact value)
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY
timestamp = (utc_date - date(1970, 1, 1)).days * DAY
如何根据 UTC 将日期转换为自纪元以来的秒数?
将已经以 UTC 表示时间的 datetime.datetime(不是 datetime.date)对象转换为相应的 POSIX 时间戳(float)。
Python 3.3+
datetime.timestamp():
from datetime import timezone
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
注意:必须明确提供timezone.utc,否则.timestamp() 假定您的天真日期时间对象位于本地时区。
Python 3 (
来自datetime.utcfromtimestamp() 的文档:
没有从 datetime 实例中获取时间戳的方法,
但是对应于日期时间实例 dt 的 POSIX 时间戳可以是
很容易计算如下。对于一个天真的 dt:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
对于有意识的 dt:
timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)
有趣的阅读:Epoch time vs. time of day 关于现在几点了?和已经过了多少秒?
另见:datetime needs an "epoch" method
Python 2
为 Python 2 改编上述代码:
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
其中timedelta.total_seconds() 相当于(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 在启用真除法的情况下计算得出。
from __future__ import division
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
# return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6
now = datetime.utcnow()
print now
print totimestamp(now)
小心floating-point issues。
输出
2012-01-08 15:34:10.022403
1326036850.02
如何将感知的datetime 对象转换为 POSIX 时间戳
assert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+
在 Python 3 上:
from datetime import datetime, timedelta, timezone
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)
integer_timestamp = (dt - epoch) // timedelta(seconds=1)
在 Python 2 上:
# utc time = local time - utc offset
utc_naive = dt.replace(tzinfo=None) - dt.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()