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

走远了吗. 提交于 2020-06-11 10:42:26

问题


In python, by importing datetime module and using various functions of class datetime.datetime we could get basic dates with formatting and even date arithmetic for deployment.

For example, datetime.datetime.now() will return today's date.

But, today when I run this program there was no internet connection in my computer but still it outputs today's date.

So, how datetime.datetime.now() could return proper date? Is the algorithm automatically increment after 24 hours time ?


回答1:


tl;dr datetime.datetime.now() uses the clock built into your computer.

Computers have been able to keep fairly accurate time for much longer than the Internet has existed.

For example, PCs feature what's called a real-time clock (RTC). It is battery-powered and can keep the time even when the computer is switched off.

Interestingly, some distributed algorithms require very accurate clocks in order to operate reliably. The required accuracy far exceeds anything that a simple oscillator-based clock can provide.

As a result, companies like Google operate 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, when some GPS clocks were out by 13 microseconds for ten hours).

Even though the data centres are connected to the Internet, neither GPS nor atomic clocks require an Internet connection to operate. Besides, someone needs to keep all that Internet time infrastructure running... it can't be that everyone gets their time "off the Internet". ;)

Now that we're on the subject of distributing the time across computer networks, the main protocols for doing that are NTP (Network Time Protocol) and PTP (Precision Time Protocol).




回答2:


The documentation for datetime.datetime.now() does not state the time is received from the 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().

The datetime is received from the computer time, if you are running windows for example, try to change time from the window and the python will print the time that you changed.

check its documentation : https://docs.python.org/2/library/datetime.html



来源:https://stackoverflow.com/questions/45831987/how-datetime-datetime-now-works-without-internet-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!