Python: datetime tzinfo time zone names documentation
The standard library does not define any timezones -- at least not well (the toy example given in the documentation does not handle subtle problems like the ones mentioned here). For predefined timezones, use the third-party pytz module.
import pytz
import datetime as DT
eastern = pytz.timezone('US/Eastern')
utc = pytz.utc
test = '2013-03-27 23:05'
This is a "naive" datetime:
test2 = DT.datetime.strptime(test, '%Y-%m-%d %H:%M')
print(test2)
# 2013-03-27 23:05:00
This makes a timezone-aware datetime by interpreting test2
as if it were in the EST timezone:
print(eastern.localize(test2))
# 2013-03-27 23:05:00-04:00
This makes a timezone-aware datetime by interpreting test2
as if it were in the UTC timezone:
print(utc.localize(test2))
# 2013-03-27 23:05:00+00:00
Alternatively, you can convert one timezone-aware datetime to another timezone using the astimezone
method:
test2_eastern = eastern.localize(test2)
print(test2_eastern.astimezone(utc))
# 2013-03-28 03:05:00+00:00
since the release of Python 3.9, the standard lib does define time zones, and you can get them via
import zoneinfo
print(zoneinfo.available_timezones())
# {'America/Belem', 'Asia/Tel_Aviv', 'Australia/North', 'Asia/Omsk',
# 'Europe/Isle_of_Man', 'America/New_York', 'Europe/Nicosia',
# 'Pacific/Funafuti', 'America/Ensenada', 'Europe/Mariehamn',
# 'America/Maceio', 'America/Guatemala', 'America/Guadeloupe', ...
- docs - zoneinfo
- see also List of tz database time zones
- on Windows: make sure to have tzdata installed and up-to-date
As mentioned by @MrFuppes, starting from python 3.9 you don't need to install 3rd party pytz
but use natively zoneinfo
.
from datetime import datetime
from zoneinfo import ZoneInfo
test = '2013-03-27 23:05'
test2 = datetime.strptime(test,'%Y-%m-%d %H:%M')
date_string = test2.replace(tzinfo=ZoneInfo('US/Eastern'))
print(datestring)
2013-03-27 23:05:00-04:00
import pytz
timezones=pytz.all_timezones
This gives all timezones