Code

Parsing Dates

datetime.strptime ("string parse time") turns text into a datetime using a format of % codes:

Code Meaning Example
%Y 4-digit year 2026
%m month number 11
%d day of month 25
%b short month name Nov
%H:%M hour:minute (24h) 21:04
from datetime import datetime

dt = datetime.strptime("25/11/2026 21:04", "%d/%m/%Y %H:%M")
dt.year, dt.hour           # (2026, 21)
d = dt.date()              # just the date part
d.strftime("%d %b %Y")     # '25 Nov 2026'  (the reverse: format)

If the text doesn't fit the format, strptime raises ValueError. Subtracting two dates gives a timedelta, whose .days is the gap:

from datetime import date
(date(2026, 12, 25) - date(2026, 11, 25)).days   # 30

Assignment

Pythonia's ledgers use three date styles, listed in FORMATS.

  1. parse_any(text) tries each format in order and returns the first that works as a date (not a datetime). If none fit, raise ValueError.
  2. days_between(start, end) takes two date strings (any of the styles) and returns the number of days from start to end as an int.