'Python datetime.now in cygwin console is incorrect
If you could help me understand why: From Cygwin terminal:
This is correct:
$ date
Wed, Sep 2, 2020 11:19:07 PM
This is also correct:
$ date --utc
Wed, Sep 2, 2020 9:19:14 PM
Timezone is also correct:
$ echo $TZ
Europe/Zurich
But when ask for local time in Python3 from the same Cygwin terminal it shows this:
$ python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2020, 9, 2, 22, 20, 4, 339547)
The hour is wrong? It shows 22h20m4s but it should be 23h20h4s as shown previously.
What am I missing?
Thanks
Solution 1:[1]
you are using Windows Python and not Cygwin one.
The cygwin one matches with the rest of Cygwin programs
$ python3
Python 3.8.3 (default, May 23 2020, 15:50:53)
[GCC 9.3.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2020, 9, 2, 23, 45, 26, 525415)
>>> quit()
$ date
Wed, Sep 2, 2020 11:45:40 PM
Solution 2:[2]
… and likely reasons are explained here: https://stackoverflow.com/a/11655109
In short: cygwin sets TZ
environment variable to the value which is not
properly understood by msvc libc, so program built with visual C++
(like official non-cygwin python which was used above) and started from cygwin will use
incorrect timezone for localtime.
unset TZ
before starting such a program should help (but of course it will break cygwin-compiled programs). Not sure whether TZ="" python3
would suffice (empty variable is still variable…)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | matzeri |
Solution 2 | Mekk |