Dates and Times
Model real moments in code: build them, do arithmetic on them, and turn them into text and back
datetime module gives you real objects that understand all of this, so you stop juggling raw numbers and strings by hand.
- create
date,timeanddatetimeobjects and read their fields, - measure and shift time with
timedelta, - turn a
datetimeinto text withstrftimeand read text back withstrptime, - explain the difference between a naive and an aware datetime, and attach a time zone.
1. Why time is harder than it looks
Think of a specific moment — say, the instant a train leaves. To pin it down you need a calendar part (which day) and a clock part (which time of day), and sometimes a third thing: where on Earth that clock is running. Two people can say "3 o'clock" and mean moments hours apart.
Analogy: a plain number like 1500 is like a photo with no caption — is it minutes, a year, a price? A datetime object is the same photo with a caption: it knows 1500 means the year, that 30 is a valid minute but not a valid month, and that adding one day to 31 January lands on 1 February, not 32 January. That built-in knowledge is exactly why we prefer objects over doing date maths on bare integers.
If you try to store a date as a string like "2026-07-15" and then ask "what is 45 days later?", you are stuck — strings do not do arithmetic. Convert to a datetime first, do the maths, then convert back to a string when you need to show it.