Python - Datetime not accounting for leap second properly?
我正在分析一些具有闰秒时间戳datetime
1 2 3 | nofrag, frag = t.split('.') nofrag_dt = datetime.datetime.strptime(nofrag,"%Y-%m-%dT%H:%M:%S") dt = nofrag_dt.replace(microsecond=int(frag)) |
python文档声称这不应该是一个问题,因为
1 2 | nofrag_dt = datetime.datetime.strptime(nofrag,"%Y-%m-%dT%H:%M:%S") ValueError: second must be in 0..59 |
号
谢谢
Unlike the time module, the datetime module does not support leap seconds.
号
时间字符串
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
执行此操作:
1 2 3 4 5 6 7 8 | 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) |
输出为:
1 | 2012-07-01 00:00:00.209215 |
号