Python - 日期时间没有正确计算闰秒?

标签 python datetime leap-second

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

    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 接受 [0, 61]。但是,我在上面的时间戳中得到了这个错误

nofrag_dt = datetime.datetime.strptime(nofrag, "%Y-%m-%dT%H:%M:%S")
ValueError: second must be in 0..59

谢谢

最佳答案

The documentation for %S 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

关于Python - 日期时间没有正确计算闰秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21027639/

相关文章:

ruby-on-rails - Rails jbuilder DateTime 将小数添加到秒

java - 为什么java tzupdater要添加闰秒?

Python - 未找到连接适配器

python - Discord.py 嵌入本地文件

php - 在给定 ISO 8601 日期时间和时区的情况下在 PHP 中获取本地时间

go - golang RFC3339Nano 时间戳是否可以可靠地与 Unix 时间戳相互转换?

java - 为什么Java Unix时间和日历计算精确时间?

python - ImportError : No module named flask. ext.login 即使安装了 Flask

python - 如何在不使用 csv 模块的情况下提取 csv 文件的内容并将其放入 dict 文件类型中。 [Python]

php - 在Wordpress中获取默认日期格式