2

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?

alex
  • 925
  • 1
  • 7
  • 9
  • 1
    Your OS knows the timezone, but not necessarily in a form that `pytz` can understand. See http://stackoverflow.com/questions/13218506/how-to-get-system-timezone-setting-and-pass-it-to-pytz-timezone – Mark Ransom Jan 11 '16 at 16:04

1 Answers1

1

On a platform with /bin/date (non-Windows), to print the current local time in a given format:

>>> import time
>>> time.strftime('%F %T %Z')
'2016-01-12 08:12:50 CET'

To reproduce it portably, you need tzlocal that finds pytz tzinfo that corresponds to your local timezone:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # pip install tzlocal

local_time = datetime.now(tzlocal.get_localzone())
print(local_time.strftime('%Y-%m-%d %H:%M:%S%z (%Z)'))
# -> 2016-01-12 08:12:51+0100 (CET)

%F, %T are not portable.

This code works even during a DST transition when the local time may be ambiguous.

jfs
  • 399,953
  • 195
  • 994
  • 1,670