How to test if a given time-stamp is in seconds or milliseconds?

后端 未结 4 460
青春惊慌失措
青春惊慌失措 2021-02-03 19:45

Assume a given variable, it is containing a UNIX time-stamp, but whether it is in seconds or milliseconds format is unknown, I want to assign to a variable which i

4条回答
  •  梦毁少年i
    2021-02-03 20:12

    An alternative to the answer given by Martin:

    We've encountered this problem when we had to unify timestamps for documents coming in from 3rd parties. While the previous condition was:

    if date > time.time():
        use_miliseconds(date)
    else:
        use_seconds(date)
    

    , and it seems like it should work, there are edge cases, especially if date was derived from a string representation without timezone info, or the clocks are being changed.

    A safer variant would be to use:

    if date > time.time() + HUNDRED_YEARS:
        use_miliseconds(date)
    else:
        use_seconds(date)
    

    , where HUNDRED_YEARS = 100 * 365 * 24 * 3600. This condition is much more error prone, in fact, it works for any date except January and February 1970 (which are ambiguous either way).

提交回复
热议问题