Binder Link: https://bit.ly/2W7TEAD (Full link)
Repository link: https://github.com/pganssle-talks/pycon-us-2019-dealing-with-datetimes
WiFi information:
datetime.datetime
¶datetimes
are immutable¶dt = datetime(2019, 5, 1, 13)
try:
dt.year = 2020
except Exception as e:
print(repr(e))
AttributeError("attribute 'year' of 'datetime.date' objects is not writable")
Use the replace
method to get a new datetime
with one or more properties modified:
dt.replace(year=2020)
datetime.datetime(2020, 5, 1, 13, 0)
dt.replace(year=2020, minute=30)
datetime.datetime(2020, 5, 1, 13, 30)
datetime.timedelta
¶from datetime import timedelta
dt_dst = datetime(2019, 11, 2, 12, tzinfo=tz.gettz("America/New_York"))
dt_std = dt_dst + timedelta(hours=24)
print(dt_dst)
print(dt_std)
2019-11-02 12:00:00-04:00 2019-11-03 12:00:00-05:00
print(dt_std.astimezone(tz.UTC) - dt_dst.astimezone(tz.UTC))
1 day, 1:00:00
print(datetime(2019, 5, 1, 13))
2019-05-01 13:00:00
print(datetime(2019, 5, 1, 13, tzinfo=tz.gettz("America/New_York")))
2019-05-01 13:00:00-04:00