将日期时间转换为 POSIX 时间

问题描述 投票:0回答:6

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

python datetime posix
6个回答
64
投票
import time, datetime

d = datetime.datetime.now()
print time.mktime(d.timetuple())

23
投票

对于 UTC 计算,

calendar.timegm
time.gmtime
的倒数。

import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())

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)

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

1
投票

这取决于

您的日期时间对象是否了解时区?

时区感知

如果知道的话就很简单(并且推荐

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

as date.timestamp() 为您提供“POSIX 时间戳”

注意:更准确地称其为 epoch/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 通常会假设它们是当地时间,这可能会让你陷入困境)

注意:还要小心您对纪元的理解,因为它依赖于平台


0
投票

从 posix/epoch 到日期时间时间戳的最佳转换以及相反:

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)
© www.soinside.com 2019 - 2024. All rights reserved.