datetime.datetime.now() 如何在没有互联网连接的情况下工作?

How datetime.datetime.now() works without internet connection?

在python中,通过导入datetime模块并使用class datetime.datetime的各种函数,我们可以获得带格式的基本日期,甚至是用于部署的日期算法。

例如,datetime.datetime.now() 将 return 今天的日期。

但是,今天当我 运行 这个程序时,我的电脑没有互联网连接,但它仍然输出今天的日期。

那么,datetime.datetime.now() 怎么 return 合适的日期呢?算法会在24小时后自动递增吗?

tl;dr datetime.datetime.now() 使用计算机内置的时钟。

计算机能够保持相当准确的时间的时间比互联网存在的时间长得多。

例如,PC 具有所谓的 real-time clock (RTC)。它是电池供电的,即使在计算机关闭时也能保持时间。

有趣的是,一些分布式算法require very accurate clocks为了可靠地运行。所需的精度远远超过简单的基于振荡器的时钟所能提供的精度。

因此,像 Google 这样的公司在运营 GPS and atomic clocks in their data centres (and even those are not without potential issues, as was demonstrated, for example, on 26 January 2017 时,一些 GPS 时钟会在 10 小时内出现 13 微秒的误差)。

即使数据中心已连接到 Internet,但 GPS 和原子钟都不需要 Internet 连接即可运行。此外,someone 需要保留所有互联网时间基础设施 运行...不可能每个人都有自己的时间 "off the Internet"。 ;)

现在我们正在讨论跨计算机网络分配时间的主题,主要的协议是 NTP (Network Time Protocol) and PTP (Precision Time Protocol)

datetime.datetime.now() 的文档未说明从 Internet 接收的时间。

Return the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).

If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcnow().replace(tzinfo=tz)). See also today(), utcnow().

datetime是从电脑收到的时间,如果你是运行比如windows,试试把时间从window和python 将打印您更改的时间。

查看其文档:https://docs.python.org/2/library/datetime.html