python - 在 Python 中将 datetime.date 转换为 UTC 时间戳

我正在处理 Python 中的日期,我需要将它们转换为 UTC 时间戳以供使用 在 Javascript 中。以下代码不起作用:

>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)

首先将日期对象转换为日期时间也无济于事。我尝试了这个 link 的示例来自,但是:

from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)

现在要么:

mktime(utc.localize(input_date).utctimetuple())

mktime(timezone('US/Eastern').localize(input_date).utctimetuple())

确实有效。

如此笼统的问题:如何根据 UTC 将日期转换为自纪元以来的秒数?

最佳答案

如果 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 的午夜不是同一时间实例,

timestamp1timestamp2 可能会有所不同。

如果 d 对应于 ambiguous local time (e.g., during DST transition) 或如果 d 是过去( future )日期,则

mktime() 可能会返回错误结果utc 偏移量可能不同并且 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() 的文档:

There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

And for an aware 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 在启用真除法的情况下计算。

Example

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()

https://stackoverflow.com/questions/8777753/

相关文章:

python - 将标准输出重定向到 Python 中的文件?

python - 测试 Python 中是否存在可执行文件?

python - 得到一系列列表的笛卡尔积?

python - 默认字典的默认字典?

python - '太多的值无法解包',迭代一个字典。键=>字符串,值=>列表

python - 在 Python 3 中从 Web 下载文件

python - 为什么 'x' 中的 ('x' 比 'x' == 'x' 快?

python - 如何计算 ndarray 中某个项目的出现次数?

python - 如何将 time.struct_time 对象转换为 datetime 对象?

python - 如何在 Python 中获取当前模块中所有类的列表?