将float转换为datetime时参数无效 [英] Invalid argument when converting float to datetime
本文介绍了将float转换为datetime时参数无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须使用Python从浮点数中获取 datetime
。我尝试使用以下代码:
I have to get a datetime
from a float using Python. I am tryint to use the following code:
import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))
但是执行此代码时,出现错误:
But when executing this code, I get an error:
OSError: [Errno 22] Invalid argument
sys.float_info.max
显示 1.7976931348623157e + 308
。
我如何将此浮点数转换为 datetime
?
How do I convert this float number into a datetime
?
推荐答案
您的操作系统似乎正在使用 ISO 8601:2004(条款4.3.2.1格里高利历),其纪元为0年。可以通过将正确的零偏移量应用为以下格式来转换:
It looks like your OS is using the ISO 8601:2004 (clause 4.3.2.1 The Gregorian calendar) with the epoch at Year 0. This can be converted by applying the correct zero offset as:
代码:
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
这篇关于将float转换为datetime时参数无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文