Python 3:将小数转换为日期时间
Python 3: Convert decimals to date time
我有一个 Json 内容:
{
"Name": "startTime",
"Value": [
{
"Valid": true,
"Time": 43852.491953472221
}
]
}
其中小数 43852.491953472221 中的 "Time" 告诉我自 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)
请注意,您给出的具体示例是未来 2 天(47 小时 20 分钟左右)。
如果您的意思是今天,并留出一定的时间来创建您的post,那么您对纪元的解释不太正确。您可能有一个; the epoch is really 1899-12-31 00:00:00, with a 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)
我有一个 Json 内容:
{
"Name": "startTime",
"Value": [
{
"Valid": true,
"Time": 43852.491953472221
}
]
}
其中小数 43852.491953472221 中的 "Time" 告诉我自 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)
请注意,您给出的具体示例是未来 2 天(47 小时 20 分钟左右)。
如果您的意思是今天,并留出一定的时间来创建您的post,那么您对纪元的解释不太正确。您可能有一个
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)