I am looking for a quick way to type in a time and then python convert it into other timezones ( maybe up to 10 different timezones )
Sorry. I am not familar with time in python at all, if someone could put me in the right direction I would really appreciate it.
Using pytz
To convert a time in one timezone to another timezone in Python, you could use
datetime.astimezone()
:Given
aware_dt
(adatetime
object in some timezone), to convert it to other timezones and to print the times in a given time format:If
f""
syntax is unavailable, you could replace it with"".format(**vars())
where you could set
aware_dt
from the current time in the local timezone:Or from the input time string in the local timezone:
where
time_string
could look like:'2016-11-19 02:21:42'
. It corresponds totime_format = '%Y-%m-%d %H:%M:%S'
.is_dst=None
forces an exception if the input time string corresponds to a non-existing or ambiguous local time such as during a DST transition. You could also passis_dst=False
,is_dst=True
. See links with more details at Python: How do you convert datetime/timestamp from one timezone to another timezone?For Python timezone conversions, I use the handy table from the PyCon 2012 presentation by Taavi Burns.
I have found that the best approach is to convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects).
Then you can use astimezone to convert to the timezone of interest (reference).
So, with the moment of interest in the local timezone (a time that exists), you convert it to utc like this (reference).
Please note: The first part of this answer is or version 1.x of pendulum. See below for a version 2.x answer.
I hope I'm not too late!
The pendulum library excels at this and other date-time calculations.
Answer lists the names of the time zones that may be used with pendulum. (They're the same as for pytz.)
For version 2:
some_time_zones
is a list of the names of the time zones that might be used in a programheres_a_time
is a sample time, complete with a time zone in the form '-0400'show_time_zones
...
-
dt
: date time stringtz1
: initial time zonetz2
: target time zone-
-