将float转换为datetim时参数无效

2024-04-24 23:30:53 发布

您现在位置:Python中文网/ 问答频道 /正文

{1}必须使用cda}从Python获取。我尝试使用以下代码:

import time
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261))))

但在执行这段代码时,我得到一个错误:

^{pr2}$

sys.float_info.max显示1.7976931348623157e+308。在

如何将这个浮点数转换成datetime?在


Tags: 代码importinfodatetimetime错误sysfloat
2条回答

试试这个:

import datetime
print datetime.datetime.fromtimestamp(63650571169.50261)
#3987-01-03 05:12:49.502609

看起来您的操作系统使用的是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)

测试代码:

^{pr2}$

结果:

2017-01-01 10:12:49.502609

相关问题 更多 >