In Europe, daylight saving time ends early in the morning on Sunday, October 27, 2024. At 3:00 AM, clocks are set back to 2:00 AM, adding an extra hour to the night. During daylight saving, Central European Summer Time (CEST) is UTC +2 hours. After the switch, Central European Time (CET) is UTC +1 hour.
Let's calculate how many hours of sleep someone in Germany would get if they go to bed on Saturday at 9:00 PM (CEST) and set their alarm for 9:00 AM (CET) the next morning.
from zoneinfo import ZoneInfo
from datetime import datetime
berlin = ZoneInfo("Europe/Berlin")
sat = datetime(2024, 10, 26, 21, 0, tzinfo=berlin)
sun = datetime(2024, 10, 27, 9, 0, tzinfo=berlin)
assert sat.isoformat() == '2024-10-26T21:00:00+02:00'
assert sun.isoformat() == '2024-10-27T09:00:00+01:00'
diff = sun - sat
Python natively provides datetime arithmetic that includes timezone information. According to the ZoneInfo documentation:
"[...] Datetimes constructed this way are compatible with datetime arithmetic and handle daylight saving time transitions with no further intervention."
The Python code provided defines two points in time using Berlin's timezone. To compute the time difference between going to bed and the alarm, we subtract the two datetimes with their respective timezone adjustments.
How long is the timedelta diff
?