Python 3 datetime.fromtimestamp fails by 1 microsecond

前端 未结 2 1432
深忆病人
深忆病人 2021-01-19 20:57

I want to save datetimes with microsecond resolution as timestamps. But it seems that Python 3 datetime module lost one microsecond when loading them. To test this let\'s cr

2条回答
  •  野的像风
    2021-01-19 21:03

    A timestamp is a POSIX time, which is essentially conceptualized as an integer number of seconds since an arbitrary "epoch". datetime.fromtimestamp() returns "the local date and time corresponding to the POSIX timestamp, such as is returned by time.time()" whose documentation tells us it "Return[s] the time in seconds since the epoch as a floating point number. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second."

    Expecting six decimal digits of precision to be retained through a conversion to and back from a timestamp seems a little unreasonable when the intermediate data type doesn't in fact guarantee sub-second accuracy. Floating point numbers are unable to represent all decimal values exactly.

    EDIT: The following code tests which microsecond values are invalid for an arbitrary datetime when the program is run.

    from datetime import datetime
    baset = datetime.now()
    
    dodgy = []
    for i in range(1000000):
        d = baset.replace(microsecond=i)
        ts = d.timestamp()
        if d != datetime.fromtimestamp(ts):
            dodgy.append(i)
    print(len(dodgy))
    

    I got 499,968 "dodgy" times, but I haven't examined them.

提交回复
热议问题