0

I'm using Python 3.8. I have an expression that gives me the local timezone

datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo

It prints out "EDT". How do I take the above and convert it to words? E.g. I would want the result to be something like

America/New_York

Not sure what the proper terminology is for the above, but it's what you get if you run this in a shell

ls -la /etc/localtime | cut -d/ -f8-9
Dave
  • 15,639
  • 133
  • 442
  • 830
  • did you have a look at `tzlocal`, as e.g. described [here](https://stackoverflow.com/questions/35057968/get-system-local-timezone-in-python)? On Linux, I think it should work with the `dateutil` method; on Windows the `tzlocal` package works fine for me (uses `pytz`) but needs to fall back on some more rigorous methods (than read from /etc/localtime) to extract the name of the local time zone. – FObersteiner Sep 22 '20 at 18:57
  • Which answer are you referring to -- "datetime.now(tzlocal())"? That doesn't print out timezone in words if that's what you meant. – Dave Sep 22 '20 at 19:47

2 Answers2

0

The following gives me what you want on my machine:

#!pip install tzlocal
from tzlocal import get_localzone
str(get_localzone())
'Europe/Moscow'

Alternatively:

from subprocess import getstatusoutput
getstatusoutput("ls -la /etc/localtime | cut -d/ -f7-9")[1]
'Europe/Moscow'
Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72
0

assuming you want the IANA time zone name or the abbreviation that indecates the UTC offset, you could use the tzlocal package (currently uses pytz internally):

from datetime import datetime
from tzlocal import get_localzone

# a datetime object aware of the local time zone:
dt = datetime.now().astimezone(get_localzone())

# the __str__ method of the tzinfo gives you the IANA name:
str(dt.tzinfo)
>>> 'Europe/Berlin'

# the _tzname attribute is the abbreviated form:
dt.tzname() # == dt.tzinfo._tzname
>>> 'CEST'

# ...which is what you also get from strftime('%Z'):
dt.strftime('%Z')
>>> 'CEST'

Side note: using dateutil.tz.tzlocal did not work out for me, neither in a Windows nor in a Unix environment. It just allows to get the abbreviated tz name, not the full IANA name.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72