Python - 获取当前 UTC 时间。总是忽略电脑时钟

Python - Get current UTC time. Ignore computer clock always

有没有人有任何提示可以从某个地方在线获取当前的 UTC 时间,并编写一些像样的 python 代码假设我的计算机时钟总是错误的?

current_datetime = datetime.datetime.utcnow() #---> assume always wrong
current_datetime = datetime.datetime.now()    #---> assume always wrong

使用“.utcnow()”或“.now()”都取决于我的计算机时钟的准确性。 我想编写代码,假设如果它从一台时钟有问题的计算机上运行,​​它仍然会得到正确的时间。

背景:

我正在尝试重组我的代码以完全使用 UTC 时间。 我的用例是做一些时间序列分析。 在进行计算时,我总是发现自己不小心偏离了美国东部标准时间 5 小时,或者偏离了夏令时 1 小时。 datetime.datetime 对象中的工具很棒,但是如果能够在导入日期时间库时标记一些设置并防止完全读取我的计算机时钟,以避免任何意外的时钟故障问题,那就太好了。

我正在寻找的代码示例:

import datetime
import requests

#force datetime libaries to never read my computer clock:
datetime.some_settings_function( readcomputerclock = False/'Never' )

#get the current time with some API:
current_utc_date_and_time_from_online = requests.get(...) #some api get request
current_utc_datetime = transform( current_utc_date_and_time_from_oneline )

#Transform back and forth to UTC Epoch time:
current_utc_epoch = current_utc_datetime.timestamp()
current_utc_datetime_again = datetime.datetime.fromtimestamp(current_utc_epoch)
#current_utc_datetime == current_utc_datetime_again

#Trigger exception with new settings, when i accidentally write code 
#    that would ask datetime library to attempt to read computer clock:
fail_code_line = datetime.datetime.now()
# >>> trigger some exception here 

TLDR;我正在为 python 寻找可靠的 UTC api,以及防止 datetime 再次读取我的计算机时钟的方法。

更新:在接受提供的答案后,我的目的变得很清楚,在从可信来源更新我的计算机时钟后信任我的计算机时钟几秒钟,然后在这些时间范围内向我的计算机时钟询问 UTC 时间几秒钟就足够了。使用已接受答案中的所有信息编写“立即获取 UTC 时间”代码是一种可行的编码实践,该代码精确到一两秒以内。 (不,我还没有对准确性进行后验统计置信区间)然后编写我的所有其余代码,使所有逻辑都采用 UTC 时间。

获得正确的、时区感知的日期时间和 unix 时间戳

原来这个问题是关于如何与 unix 时间戳和日期时间相互转换。

python3的正确解法应该是:

from datetime import datetime, timezone

# get the current utc time
t = datetime.now(timezone.utc)

# convert to unix, this will keep the utc timezone
unix = t.timestamp()

# convert back to datetime, specifying that the timestamp is in UTC
t2 = datetime.fromtimestamp(unix, tz=timezone.utc)

其他时区

从python 3.9 开始,stdlib 有zoneinfo 库,您可以使用它在时区之间进行转换。 对于 python < 3.9,您必须使用像 dateutil.

这样的第三方库
from datetime import datetime
from zoneinfo import ZoneInfo

now_berlin = datetime.now(ZoneInfo('Europe/Berlin'))
now_ny = now_berlin.astimezone(ZoneInfo('America/New_York'))

print('Time in Berlin:', now_berlin)
print('Time in New York', now_ny)

实际使用的是ntp而不是电脑时钟

您可以使用 ntplib:

from ntplib import NTPClient
from datetime import datetime, timezone

client = NTPClient()
response = client.request('europe.pool.ntp.org', version=3)

time = datetime.fromtimestamp(resp.tx_time, tz=timezone.utc)

编辑:但是我没有看到真正的原因,为什么仅仅因为旅行就会出错:

from datetime import datetime, timezone

dt = datetime.now(timezone.utc)

有关详细信息,请参阅:https://blog.ganssle.io/articles/2019/11/utcnow.html