python - 将 float 转换为日期时间时参数无效

标签 python datetime time

我必须使用 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/

相关文章:

python - 将复杂的 Matlab 引擎数组高效转换为 numpy ndarray

python - 在配置文件中使用字典而不是列表是一个坏习惯吗?

python - dateutil 解析器用于月/年格式 : return beginning of month

ruby - 日期、日期时间和时区

用于触发时间同步的 Windows API

c++ - struct 和 time_t 的计算错误

python - 使用字典计算 python 数据框中的词频

datetime - 使用 moment.js 使用语言环境而不是显式格式设置日期格式

java - 分离日期和时间对象

python - 减少 Python 递归深度的方法