Dates and Times
About 18 minutes
Why this matters
Dates look easy until you meet leap years, month lengths and weekends. The datetime module does the hard parts, so you never count days by hand.
The idea
from datetime import date, datetime, timedelta
d = date(2024, 3, 5) # year, month, day
d.year, d.month, d.day # 2024 3 5
d.weekday() # 1 (Monday is 0, Sunday is 6)
d + timedelta(days=30) # date(2024, 4, 4)
date(2024, 12, 25) - d # timedelta(days=295)
(date(2024, 12, 25) - d).days # 295
d.strftime("%d %B %Y") # '05 March 2024' (date -> text)
datetime.strptime("2024-03-05", "%Y-%m-%d").date() # text -> date
Common format codes: %Y year, %m month number, %d day, %B month name, %A weekday name, %H:%M hours and minutes. date.today() gives today’s date, but functions that take the date as a parameter are much easier to test.
Try it
Work out how many days there are from today until the end of the year. Then print today’s weekday name with strftime("%A").
Your turn
Write four functions:
days_until(today, target): the number of days fromtodaytotarget, bothdateobjects. It is negative whentargetis in the past.format_date(d): text like05 March 2024.parse_date(text): turn"2024-03-05"into adate. Other formats raiseValueError.add_business_days(start, n): the datenbusiness days afterstart, skipping Saturdays and Sundays. From Friday 8 March 2024, one business day later is Monday 11 March.
Recap
dateholds a day,timedeltaa length of time; subtract dates to get atimedelta.strftimeformats a date as text;strptimeparses text into a date.- Pass dates into functions instead of calling
date.today()inside, so they can be tested.
Common mistakes
- Mixing up
dateanddatetime:TypeError: can't compare datetime.datetime to datetime.date. - Wrong format codes (
%mis the month number,%Mis minutes), which raiseValueErrorwhen parsing. - Forgetting that Monday is 0, so weekdays are 0 to 4.