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

Question:

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.

enter image description here

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 increments after 24 hours time ?

Asked By: S.Rakin

||

Answers:

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).

Answered By: NPE

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

Answered By: Ali Ezzat Odeh