Python 3 : Convert decimals to date time

标签 python python-3.x decimal datetime-format

我有一个包含内容的 Json:

{
    "Name": "startTime",
    "Value": [
        {
            "Valid": true,
            "Time": 43852.491953472221
        }
    ]
}

据我所知,小数点后的“时间”43852.491953472221 表示自 1900 年 1 月 1 日以来的天数。

有没有快速的方法可以将Python中的时间转换为如下格式:

import time
print("Start time: ", time.ctime(time.time()))

输出:

Start time:  Wed Jan 22 14:10:50 2020

最佳答案

使用 datetime.timedelta() 对象以及纪元的 datetime.datetime() 值:

from datetime import datetime, timedelta

EPOCH = datetime(1900, 1, 1)  # midnight 1st January 1900

def from_ordinal(ordinal, _epoch=EPOCH):
    return _epoch + timedelta(days=ordinal)

演示:

>>> from_ordinal(43852.491953472221)
datetime.datetime(2020, 1, 24, 11, 48, 24, 780000)

请注意,您给出的具体示例是 future 2 天(47 小时 20 分钟或左右)。

如果您的意思是今天,并且有足够的时间来创建您的帖子,那么您的纪元解释不太正确。您可能有一个 Excel decimal timestamp value ;纪元实际上是 1899-12-31 00:00:00,带有 leap-year bug-as-feature inherited from Lotus 1-2-3 ,在这种情况下,您需要为任何等于或大于 60 的值减去 1:

EXCEL_EPOCH0 = datetime(1899, 12, 31)

def from_excel_ordinal(ordinal, _epoch=EXCEL_EPOCH0):
    if ordinal >= 60:
        ordinal -= 1  # Excel / Lotus 1-2-3 leap year bug, 1900 is not a leap year!
    # Excel doesn't support microseconds, ignore them as mere fp artefacts
    return (_epoch + timedelta(days=ordinal)).replace(microsecond=0)

这会产生:

>>> from_excel_ordinal(43852.491953472221)
datetime.datetime(2020, 1, 22, 11, 48, 24)

关于Python 3 : Convert decimals to date time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59859725/

相关文章:

python - 在 numpy 中生成随机 int64 数组的最简单方法?

Python将字符串与正则表达式匹配

python - 模块 `collections` 中的其他 26 个元素

python - 哪种列类型支持 sqlalchemy 中的列表?

c++ - 我如何在不知道 float 长度的情况下进行 fscanf?

Python 单元测试数据提供程序

python - Django 迁移和可解构字符串

python - 用 0 填充和对齐向量

c++ - 十进制转十六进制C++内置函数

.net - 网络 5 : Decimal silently truncated - how to make it break?