Python Module

The datetime module is handy when dealing with dates, times, and durations in Python. The four core classes are:

  • datetime.datetime - specific moment in time (2025-07-30 17:43:20)
  • datetime.timedelta - duration expressing the difference between two datetime or date instances to microsecond resolution.
  • dateime.date - calendar date (2025-07-30) asssuming gregorian calendar
  • dateime.time - time of day (17:43:20)

Common patterns to remember

  • Timestamps for filenames: datetime.now().strftime("%Y%m%d_%H%M%S")
  • Age calculations: (date.today() - birth_date).days // 365
  • Checking if recent: timestamp > datetime.now() - timedelta(hours=24)
  • Duration between events: end_time - start_time
  • Adding business days: start_date + timedelta(days=5)
  • End of day: datetime.combine(date.today(), time.max)
  • ISO format for APIs: datetime.now().isoformat()
  • Parsing user input with try/except for multiple formats

A sample of the format codes for formating the datetime objects:

CodeMeaningExample
%Y4-digit year2025
%y2-digit year25
%mMonth (01-12)07
%BFull month nameJuly
%bShort month nameJul
%dDay (01-31)30
%HHour 24-hour (00-23)14
%IHour 12-hour (01-12)02
%MMinute (00-59)30
%SSecond (00-59)45
%pAM/PMPM

Gotchas to be mindful of

  • Doesn’t work well with timezones
  • timedelta doesn’t handle months/years reliably