我必须使用 Python 从 float 中获取 datetime
。我正在尝试使用以下代码:
import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))
但是当执行这段代码时,我得到一个错误:
OSError: [Errno 22] Invalid argument
sys.float_info.max
显示 1.7976931348623157e+308
。
如何将此 float 转换为 datetime
?
最佳答案
看起来您的操作系统正在使用 ISO 8601:2004 (clause 4.3.2.1 The Gregorian calendar) 0 年的纪元。这可以通过应用正确的零偏移量来转换为:
代码:
import datetime as dt
# define some constants
epoch = dt.datetime(1970, 1, 1)
gregorian_8601_to_unix_epoch = 62167305600
def gregorian_8601_to_datetime(gregorian_8601_seconds):
# get number of seconds from epoch
from_epoch = gregorian_8601_seconds - gregorian_8601_to_unix_epoch
# convert to python datetime
return epoch + dt.timedelta(seconds=from_epoch)
测试代码:
print(gregorian_8601_to_datetime(63650571169.50261))
结果:
2017-01-01 10:12:49.502609
关于python - 将 float 转换为日期时间时参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099558/