Home > Software engineering >  How does Python determine the current time zone?
How does Python determine the current time zone?

Time:03-12

Python's documentation claims:

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

So if you call this and the documentation is true, you should get the time in your system's time zone:

import datetime
datetime.datetime.now()

On Linux, there are two ways to set the time zone: Either via the TZ environment variable, or the symlink /etc/localtime.

In a Docker container, the TZ environment variable is blank, and the localtime symlink looks like this:

# ls -l /etc/localtime
lrwxrwxrwx 1 root root 27 May 11  2021 /etc/localtime -> /usr/share/zoneinfo/Etc/UTC

There is also a file called /etc/timezone that contains Etc/UTC, but that file isn't mentioned in tzset(3), which describes how Libc handles time zone configuration.

So this means the "platform’s local date and time" should be in UTC. Naturally, the date command gives the time in UTC:

# date
Fri Mar 11 10:18:52 UTC 2022
#

But, if I start up Python 3.7.10, it seems there's another way to determine the time zone, because Python somehow decides that the "platform's local date and time" is in the Pacific time zone:

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2022-03-11T02:18:52.183474'

So obviously the documentation is incorrect. Python does not use the system time zone. It has some other way of deciding what time zone to be in. What is going on here?

CodePudding user response:

I meet the same thing. I solve it with this

CodePudding user response:

What is going on here?

Scrying datetime source gives

@classmethod
def now(cls, tz=None):
    "Construct a datetime from time.time() and optional time zone info."
    t = _time.time()
    return cls.fromtimestamp(t, tz)

thus clearly datetime.datetime.now behavior depends on time.time function, so I guess answer is somewhere inside time source but at it is not python language I will let determining that to users better understanding language in which time module is implemented.

  • Related