55

如何在 python 中将日期时间或日期对象转换为 POSIX 时间戳?有一些方法可以根据时间戳创建日期时间对象,但我似乎没有找到任何明显的方法来以相反的方式进行操作。

4

6 回答 6

59
import time, datetime

d = datetime.datetime.now()
print time.mktime(d.timetuple())
于 2008-10-31T21:44:35.070 回答
22

对于 UTC 计算,calendar.timegm是 的倒数time.gmtime

import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())
于 2011-05-03T15:39:15.637 回答
12

请注意,Python 现在(3.5.2)在对象中包含了一个用于此的内置方法datetime

>>> import datetime
>>> now = datetime.datetime(2020, 11, 18, 18, 52, 47, 874766)
>>> now.timestamp() # Local time
1605743567.874766
>>> now.replace(tzinfo=datetime.timezone.utc).timestamp() # UTC
1605725567.874766 # 5 hours delta (I'm in UTC-5)
于 2017-10-30T02:16:14.387 回答
4

在 python 中,time.time() 可以将秒作为浮点数返回,其中包括带有微秒的小数部分。为了将日期时间转换回此表示,您必须添加微秒组件,因为直接时间元组不包含它。

import time, datetime

posix_now = time.time()

d = datetime.datetime.fromtimestamp(posix_now)
no_microseconds_time = time.mktime(d.timetuple())
has_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001

print posix_now
print no_microseconds_time
print has_microseconds_time
于 2013-01-16T22:52:43.277 回答
0

从 posix/epoch 到 datetime 时间戳的最佳转换,反之亦然:

this_time = datetime.datetime.utcnow() # datetime.datetime type
epoch_time = this_time.timestamp()      # posix time or epoch time
this_time = datetime.datetime.fromtimestamp(epoch_time)
于 2019-09-23T04:33:25.427 回答
0

这取决于

您的 datetime 对象时区是感知的还是幼稚的?

时区感知

如果它知道这很简单

from datetime import datetime, timezone
aware_date = datetime.now(tz=timezone.utc)
posix_timestamp = aware_date.timestamp()

因为date.timestamp()给你“POSIX时间戳”

注意:将其称为纪元/unix 时间戳更准确,因为它可能不符合 POSIX

时区幼稚

如果它不是时区感知(天真),那么您需要知道它最初位于哪个时区,以便我们可以使用replace()将其转换为时区感知日期对象。假设您已将其存储/检索为 UTC Naive。这里我们创建一个,例如:

from datetime import datetime, timezone
naive_date = datetime.utcnow()  # this date is naive, but is UTC based
aware_date = naive_date.replace(tzinfo=timezone.utc)  # this date is no longer naive

# now we do as we did with the last one

posix_timestamp = aware_date.timestamp()

最好尽快到达时区感知日期,以防止天真的日期可能出现的问题(因为 Python 通常会认为它们是当地时间并且可能会搞砸你)

注意:还要小心您对时代的理解,因为它取决于平台

于 2020-11-18T02:19:09.100 回答