The snippet library.
Small, practical examples. Search by task or narrow things down below.
Advance a date by a number of days
Python: Use timedelta so month and year boundaries are handled automatically.
Python✓ Tested
Convert a duration to hours and minutes
Python: Use divmod to split nonnegative whole seconds into display components.
Python✓ Tested
Convert a Unix timestamp to aware UTC
Python: Supply timezone.utc so the result does not depend on the machine time zone.
Python✓ Tested
Convert an aware datetime to another offset
Python: Use astimezone for conversion; replacing tzinfo alone does not convert an instant.
Python✓ Tested
Count days between calendar dates
Python: Subtract date objects to get an exact calendar-day difference.
Python✓ Tested
Determine whether a year is a leap year
Python: Use calendar.isleap rather than a simplified divisibility-by-four check.
Python✓ Tested
Find the number of days in a month
Python: Use calendar.monthrange to account for leap years.
Python✓ Tested
Parse an ISO calendar date
Python: Use date.fromisoformat and inspect the calendar components.
Python✓ Tested
Read an ISO week number
Python: Use isocalendar because ISO week years can differ from calendar years near January.
Python✓ Tested
Skip weekends when advancing dates
Python: Walk calendar dates and count only Monday through Friday.
Python✓ Tested