I want to have a datetime formatted like %F %T %Z
in Python2. If I do it naively with datetime.now()
the timezone part appears empty. I've learned that Python2 doesn't have support for tzinfo
objects, but there's a 3rd-party pytz
module.
Unfortunately, in order to construct a tzinfo
with pytz
I still need to name the timezone explicitly. What I would like to have is a combination of localtime()
and a default tzinfo
, so that I get current time in local timezone.
Compare the following three outputs:
>>> from datetime import datetime
>>> datetime.now().strftime("%F %T %Z")
"2016-01-11 16:13:22 "
>>> import pytz
>>> datetime.now(pytz.timezone('CET')).strftime("%F %T %Z")
"2016-01-11 16:13:37 CET"
>>> from time import localtime
>>> datetime(*(localtime()[:7])).strftime("%F %T %Z")
"2016-01-11 16:14:24 "
The second one is what I want, sans the need to specify the timezone explicitly. On the other hand, /bin/date
doesn't need any hint to look the timezone up:
$ /bin/date
Mo 11. Jan 16:17:31 CET 2016
Looking at the source code for date(1)
I can see that when compiled with glibc it relies on tm_zone
field being part of struct tm
, but otherwise will require TZ
environment variable to be set.
Any ideas how to make this work with Python2 w/o hard-coding the timezone?