>>> import time
>>> time.tzname
('GMT', 'BST')
Where does Python get this information (the local timezone) from? Is there a syscall that returns this? I see some sources mentioning a /etc/timezone
file, and others mentioning a TZ
environment variable.
I see that Python honors the TZ
environment variable if set:
TZ="Asia/Calcutta" python -c "import time; print(time.tzname)"
('IST', 'IST')
My shell doesn't have this set by default though, so I'm curious how the local timezone is read when the TZ
environment variable isn't present.
CodePudding user response:
This will depends upon the platform you are using. If you are on windows, you assumption is correct, it makes GetTimeZoneInformation
system call to create the time.tzname
tuple. Here is the relevant part of the C
code.
#ifdef MS_WINDOWS TIME_ZONE_INFORMATION tzinfo = {0}; GetTimeZoneInformation(&tzinfo); otz0 = PyUnicode_FromWideChar(tzinfo.StandardName, -1); if (otz0 == NULL) { return -1; } otz1 = PyUnicode_FromWideChar(tzinfo.DaylightName, -1); if (otz1 == NULL) { Py_DECREF(otz0); return -1; } #else // Skipped for brevity #endif // MS_WINDOWS PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1); if (tzname_obj == NULL) { return -1; } PyModule_AddObject(m, "tzname", tzname_obj);
But where as in other platform it completely depends upon the tzname
variable which is initialized by the tzset()
function in the C
standard library.
The
tzset()
function initializes thetzname
variable from theTZ
environment variable. This function is automatically called by the other time conversion functions that depend on the timezone. In a System-V-like environment, it will also set the variables timezone (seconds West of UTC) and daylight (to 0 if this timezone does not have any daylight saving time rules, or to nonzero if there is a time, past, present, or future when daylight saving time applies).If the
TZ
variable does not appear in the environment, the system timezone is used. The system timezone is configured by copying, or linking, a file in the tzfile(5) format to/etc/localtime
. A timezone database of these files may be located in the system timezone directory (see the FILES section below).If the
TZ
variable does appear in the environment, but its value is empty, or its value cannot be interpreted using any of the formats specified below, then Coordinated Universal Time (UTC) is used.