Python日期时间不能正确计算闰秒?

2024-09-29 01:30:24 发布

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

我正在分析一些具有闰秒时间戳datetime2012-06-30T23:59:60.209215的数据。我使用以下代码解析该字符串并将其转换为datetime对象:

    nofrag, frag = t.split('.')
    nofrag_dt = datetime.datetime.strptime(nofrag, "%Y-%m-%dT%H:%M:%S")
    dt = nofrag_dt.replace(microsecond=int(frag))

Python文档声称这不应该是一个问题,因为%S接受{}。但是,我用上面的时间戳得到了这个错误

^{pr2}$

谢谢


Tags: 数据对象字符串代码datetime时间dtreplace
2条回答

这样做:

import time
import datetime 
t = '2012-06-30T23:59:60.209215'
nofrag, frag = t.split('.')
nofrag_dt = time.strptime(nofrag, "%Y-%m-%dT%H:%M:%S")
ts = datetime.datetime.fromtimestamp(time.mktime(nofrag_dt))
dt = ts.replace(microsecond=int(frag))
print(dt)

输出为:

^{pr2}$

The documentation for ^{} says

Unlike the time module, the datetime module does not support leap seconds.

时间字符串"2012-06-30T23:59:60.209215"表示时间以UTC表示(它是当前的最后一个闰秒):

import time
from calendar import timegm
from datetime import datetime, timedelta

time_string = '2012-06-30T23:59:60.209215'
time_string, dot, us = time_string.partition('.')
utc_time_tuple = time.strptime(time_string, "%Y-%m-%dT%H:%M:%S")
dt = datetime(1970, 1, 1) + timedelta(seconds=timegm(utc_time_tuple))
if dot:
    dt = dt.replace(microsecond=datetime.strptime(us, '%f').microsecond)
print(dt)
# -> 2012-07-01 00:00:00.209215

相关问题 更多 >