This question is really quite simple, and it's basically the title. I am in Western Australia.
This question is really quite simple, and it's basically the title. I am in Western Australia.
Yup the pytz and datetime module is the way to go:
import pytz
from datetime import datetime
timezone = 'Australia/Perth'
py_timezone = pytz.timezone(timezone)
current_datetime = datetime.now(py_timezone)
If you need to find a specific timezone you use the all_timezones property in pytz, which will return a list of all timezones.
import pytz
all_timezones = pytz.all_timezones
pytz is likely to be deprecated in the future.
The newer and better way to do this, as of Python 3.9 (currently in beta) is to use the zoneinfo module.
Current time in Amsterdam:
from datetime import datetime
from zoneinfo import ZoneInfo
now = datetime.now(tz=ZoneInfo("Europe/Amsterdam"))
Convert a time in one timezone to another:
from datetime import datetime
from zoneinfo import ZoneInfo
dt = datetime(2020, 1, 1, 12, tzinfo=ZoneInfo("Asia/Ho_Chi_Minh"))
converted_dt = dt.astimezone(ZoneInfo("Africa/Windhoek"))
Get available timezones:
import zoneinfo
zoneinfo.available_timezones()
You can use this already in Python 3.6+ with the backports.zoneinfo package.
important to notice is also that if you only want to have the local time, i.e. according to the timezone setting of your OS, you only need datetime.
from datetime import datetime
now = datetime.now()
# print(now)
# 2020-06-27 13:08:12.007814
now would be a naive datetime object, i.e. it does not know about the timezone. Python will by default assume that it belongs in your local timezone (not e.g. UTC).
You can even make it timezone-aware without any other imports:
now = now.astimezone()
# print(now)
# 2020-06-27 13:08:12.007814+02:00 # I'm on CEST at the moment; UTC+2
If you want to implement different timezones or change timezones, here's an example how to do it with dateutil:
import dateutil
awst = dateutil.tz.gettz('Australia/Perth')
now_naive = datetime.now()
now_aware = now_naive.replace(tzinfo=awst)
print(now_aware.strftime('%a %d %b %Y %H:%M:%S %z %Z'))
# Sat 27 Jun 2020 17:08:53 +0800 AWST
# same time in another timezone:
cest = dateutil.tz.gettz('Europe/Berlin')
now_aware = now_aware.astimezone(cest)
print(now_aware.strftime('%a %d %b %Y %H:%M:%S %z %Z'))
# Sat 27 Jun 2020 11:08:53 +0200 CEST
For Python 3.9 zoneinfo, the methods are basically the same so changing from dateutil to zoneinfo is feasable.