我正在解析一些具有leapsecond timestampe datetime的数据2012-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
接受的问题[0, 61]
.但是,我在上面的时间戳中得到了这个错误
nofrag_dt = datetime.datetime.strptime(nofrag, "%Y-%m-%dT%H:%M:%S") ValueError: second must be in 0..59
谢谢
文档%S
说:
与时间模块不同,datetime模块不支持闰秒.
时间字符串"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