I'm using pytz. I've read through the entire documentation sheet, but didn't see how this could be done.
I have a timezone: America/Chicago. All I want is to get the respective country code for this timezone: US.
It shows that I can do the opposite, such as:
>>> country_timezones('ch')
['Europe/Zurich']
>>> country_timezones('CH')
['Europe/Zurich']
but I need to do it the other way around.
Can this be done in Python, using pytz (or any other way for that matter)?
To get the Universal Time Coordinated i.e. UTC time we just pass in the parameter to now() function. To get the UTC time we can directly use the 'pytz. utc' as a parameter to now() function as 'now(pytz. utc)'.
The pytz module allows for date-time conversion and timezone calculations so that your Python applications can keep track of dates and times, while staying accurate to the timezone of a particular location.
The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.
The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information): >>> loc_dt = eastern. localize(datetime(2002, 10, 27, 6, 0, 0)) >>> print(loc_dt. strftime(fmt)) 2002-10-27 06:00:00 EST-0500.
You can use the country_timezones
object from pytz
and generate an inverse mapping:
from pytz import country_timezones
timezone_country = {}
for countrycode in country_timezones:
timezones = country_timezones[countrycode]
for timezone in timezones:
timezone_country[timezone] = countrycode
Now just use the resulting dictionary:
>>> timezone_country['Europe/Zurich']
u'CH'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With