gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:02 25 4
gpt4 key购买 nike

我正在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)

mktime() 可能会返回错误结果或者如果 d 是过去( future )日期,此时 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 (< 3.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()

关于python - 在Python中将datetime.date转换为UTC时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25390884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com