How to make a datetime object aware (not naive)

In general, to make a naive datetime timezone-aware, use the localize method: import datetime import pytz unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0) aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC) now_aware = pytz.utc.localize(unaware) assert aware == now_aware For the UTC timezone, it is not really necessary to use localize since … Read more

Why doesn’t pytz localize() produce a datetime object with tzinfo matching the tz object that localized it?

They are the same time zone – “Europe/Berlin”. When you are printing them, the output includes the abbreviation and offset that applies at that particular point in time. If you examine the tz data sources, you’ll see: # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Berlin 0:53:28 – LMT 1893 Apr 1:00 C-Eur CE%sT 1945 … Read more

get the DST boundaries of a given timezone in python

It doesn’t seem to be officially supported. However, you can poke at the internals of a DstTzInfo object and get it from there: >>> from pytz import timezone >>> tz = timezone(‘Europe/London’) >>> tz._utc_transition_times [datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1916, 5, 21, 2, 0), … datetime.datetime(2036, 3, 30, 1, 0), datetime.datetime(2036, 10, 26, 1, 0), … Read more

How to make a datetime object aware (not naive) in Python?

In general, to make a naive datetime timezone-aware, use the localize method: import datetime import pytz unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0) aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC) now_aware = pytz.utc.localize(unaware) assert aware == now_aware For the UTC timezone, it is not really necessary to use localize since … Read more

How do you convert a datetime/timestamp from one timezone to another timezone?

If you know your origin timezone and the new timezone that you want to convert it to, it turns out to be very straightforward: Make two pytz.timezone objects, one for the current timezone and one for the new timezone e.g. pytz.timezone(“US/Pacific”). You can find a list of all official timezones in pytz library: import pytz; … Read more