Sometimes, we want to display the time in a different time zone with Python.
In this article, we’ll look at how to display the time in a different time zone with Python.
How to display the time in a different time zone with Python?
To display the time in a different time zone with Python, we can use the pytz
module.
For instance, we write:
from datetime import datetime
from pytz import timezone
south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print(sa_time.strftime('%Y-%m-%d_%H-%M-%S'))
We call timezone
with the time zone string to get the time zone object.
Then we call datetime.now
with the time zone object to return the current date time in the south_africa
time zone.
Finally, we call strftime
to return the date time string from the date time object by calling it with a format string.
%Y
is the year.
%m
is the month.
%d
is the day.
%H
is the hour.
%M
is the minute.
And %S
is the seconds.
Therefore, we see something like '2021-10-31_22-15-22'
printed.
Conclusion
To display the time in a different time zone with Python, we can use the pytz
module.