Python datetime.utcnow() returning incorrect datetime

前端 未结 4 1863
渐次进展
渐次进展 2020-11-29 08:33
datetime.utcnow()

This call is returning an incorrect datetime, delayed from UTC/GMT by 1 hour (check in: http://www.worldtimeserver.com/current_ti

4条回答
  •  囚心锁ツ
    2020-11-29 09:17

    datetime.utcnow() uses OS provided values.

    datetime.utcnow() uses gettimeofday(2) or time.time() on Python 2 (and gmtime(3) to convert the result into broken-down time).

    time.time() uses gettimeofday(2), ftime(3), time(2). Newer CPython versions may use clock_gettime(2), GetSystemTimeAsFileTime().

    You could check the self-consistency as follows:

    #!/usr/bin/env python
    import time
    from datetime import datetime, timedelta
    
    print(datetime.utcnow())
    print(datetime(1970, 1, 1) + timedelta(seconds=time.time()))
    print(datetime(*time.gmtime()[:6]))
    

    Here's (non-tested) code that calls GetSystemTimeAsFileTime() on Windows based on CPython source:

    #!/usr/bin/env python
    import ctypes.wintypes
    from datetime import datetime, timedelta
    
    def utcnow_microseconds():
        system_time = ctypes.wintypes.FILETIME()
        ctypes.windll.kernel32.GetSystemTimeAsFileTime(ctypes.byref(system_time))
        large = (system_time.dwHighDateTime << 32) + system_time.dwLowDateTime
        return large // 10 - 11644473600000000
    
    print(datetime(1970, 1, 1) + timedelta(microseconds=utcnow_microseconds()))
    

    Here's code that calls clock_gettime() on Python 2.

提交回复
热议问题