Python datetime.utcnow() 返回不正确的日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28573873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:27:59  来源:igfitidea点击:

Python datetime.utcnow() returning incorrect datetime

pythonpython-2.7datetimeutc

提问by Johann Gomes

datetime.utcnow()

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

此调用返回不正确的日期时间,从 UTC/GMT 延迟 1 小时(请登录:http: //www.worldtimeserver.com/current_time_in_UTC.asp)。

Is it working like it should be?

它是否像应有的那样工作?

For example, it's returning, right now:

例如,它现在正在返回:

2015-02-17 23:58:44.761000.

Current UTC time is: 00:58, not 23:58

当前 UTC 时间是:00:58,而不是 23:58

回答by jfs

datetime.utcnow()uses OS provided values.

datetime.utcnow()使用操作系统提供的值。

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

datetime.utcnow()在 Python 2 上使用gettimeofday(2)time.time()gmtime(3)并将结果转换为故障时间)。

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

time.time()使用gettimeofday(2), ftime(3), time(2). 较新的 CPython 版本可能使用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:

这是基于 CPython 源GetSystemTimeAsFileTime()在 Windows调用的(未经测试的)代码:

#!/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.

这是调用clock_gettime()Python 2的代码。

回答by markling

Problem only occurs with utc time (Python3).

问题只发生在 UTC 时间(Python3)。

e.g. System time:

例如系统时间:

$ date

Wed Jul 15 10:44:26 BST 2015

Python time correct when using datetime.now():

使用 datetime.now() 时 Python 时间正确:

>>> datetime.now()

datetime.datetime(2015, 7, 15, 10, 44, 30, 775840)

...But incorrect by one hour when using datetime.utcnow():

...但在使用 datetime.utcnow() 时一小时不正确:

>>> datetime.utcnow()

datetime.datetime(2015, 7, 15, 9, 44, 32, 599823)

UTC's problem is it doesn't know my timezone.

UTC 的问题是它不知道我的时区。

You have to tell it, with the help of a timezone module called pytz:

您必须在名为 pytz 的时区模块的帮助下告诉它:

>>> import pytz
>>> mytz = pytz.timezone('Europe/London')
>>> pytz.utc.localize(datetime.utcnow(), is_dst=None).astimezone(mytz)

datetime.datetime(2015, 7, 15, 11, 3, 43, 688681, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)

References:

参考:

pytz - Converting UTC and timezone to local time

pytz - 将 UTC 和时区转换为本地时间

https://opensourcehacker.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/

https://opensourcehacker.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/

http://sweemengs-tech-world.blogspot.co.uk/2010/05/get-correct-datetime-value-for-python.html

http://sweemengs-tech-world.blogspot.co.uk/2010/05/get-correct-datetime-value-for-python.html

http://bugs.python.org/issue5094)

http://bugs.python.org/issue5094)

回答by Pramit Sood

I know I am tremendously late in replying to this.

我知道我回答这个问题太晚了。

I have tried doing this recently and therefore I suggest using datetime.now()instead of datetime.utcnow(). For my simple application that works fine.

我最近尝试过这样做,因此我建议使用datetime.now()而不是datetime.utcnow(). 对于我工作正常的简单应用程序。

回答by matkes

I know I'm five years late, but I had the same problem tonight. In my experience, the solution to the problem was to use the aware UTC datetime:

我知道我迟到了五年,但今晚我遇到了同样的问题。根据我的经验,问题的解决方案是使用感知 UTC 日期时间:

utc_dt_aware = datetime.datetime.now(datetime.timezone.utc)

If you google "utcnow() wrong" this is the first result you get, so I thought it would be good to answer anyway.

如果你用谷歌搜索“utcnow() 错误”,这是你得到的第一个结果,所以我认为无论如何回答都会很好。