我有一个包含内容的 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/