Python - Datetime not accounting for leap second properly?

前端 未结 2 1181
北恋
北恋 2020-12-06 11:07

I am parsing some data that has the leapsecond timestampe datetime 2012-06-30T23:59:60.209215. I used following code to parse that string and convert to a datet

相关标签:
2条回答
  • 2020-12-06 11:36

    The documentation for %S says:

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

    The time string "2012-06-30T23:59:60.209215" implies that the time is in UTC (it is the last leap second at the moment):

    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
    
    0 讨论(0)
  • 2020-12-06 11:49

    Do this:

    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)
    

    Output is:

    2012-07-01 00:00:00.209215
    
    0 讨论(0)
提交回复
热议问题