Use Python’s date for a calendar day and datetime for a date with a clock time. Parse supported ISO forms with fromisoformat() or a known custom format with strptime(). Use strftime() to display the result. If a timestamp identifies an instant, keep its offset or time zone.
Choose between date, time, and datetime
A birthday, invoice due date or full-day closure can be represented as a date. It does not need a clock value or implied timezone. A delivery confirmation or event arrival usually needs a datetime plus an offset or zone interpretation. An opening time such as 09:00 can be a time or a schedule rule. It does not identify a particular instant until it is paired with a date and the applicable zone.
Adding midnight to every calendar date can make a simple field harder to understand. If a due date is interpreted as midnight UTC and displayed in a negative-offset zone, it can appear on the previous local day. Preserve the date as a date unless the business rule actually defines an instant. If “due by the end of the day” matters, ask whose day and how the deadline is compared.
Parse the format you expect
from datetime import date, datetime
due = date.fromisoformat("2026-04-21")
submitted = datetime.fromisoformat("2026-04-21T17:05:00+00:00")
meeting = datetime.strptime("24/04/2026 09:30", "%d/%m/%Y %H:%M")
assert due.year == 2026
assert submitted.utcoffset().total_seconds() == 0
assert meeting.tzinfo is None
The meeting example parses a known day-first input. It yields a naive datetime because the input includes no timezone and the format supplies none. Treat it as a local wall-clock value until the source identifies the zone. An ambiguous display string such as 04/05/2026 does not reveal whether it means April 5 or May 4.
Parsing fails when the input is impossible or out of contract. February 30 is invalid even if the digits match the format. ISO-style parsers may accept forms in addition to the one you want. If an API contract requires exactly a four-digit year, two-digit month and two-digit day with hyphens, enforce the structure as well as checking the resulting date.
Format after you calculate
Store or exchange dates in a consistent machine-readable form. A string such as Apr 21, 2026 can help people read a report, but it is a weaker input for sorting or round-tripping across regions. Use isoformat() where the consumer accepts it. Use strftime("%Y-%m-%d %H:%M") for that explicit display form. Add zone or offset information if two readers may interpret the same clock time differently.
Strings that begin with a year can sort chronologically under restricted assumptions. Mixed offsets, differing precision or calendar formats can break those assumptions. Parse first and compare values using a consistent type and timezone policy. Pick the formatting afterward. A timestamp does not gain precision simply because you print fractions of a second.
Calculate durations and select a date range
Subtract matching date types to get a timedelta. For datetime durations, align your calculation with whether you mean elapsed time or a difference between clock readings. Around daylight saving transitions those can differ. Convert aware values to UTC before subtraction where you need elapsed time between instants. To express a duration in seconds, use total_seconds(). The .seconds field alone omits complete days and is not a signed total.
For monthly reports, a half-open range is useful. Include events at the month’s start and exclude events at the next month’s start. Set those boundaries in the reporting zone before comparing instants. This avoids guessing the finest valid time of the last day, and adjacent periods cannot both claim a record exactly at the boundary.
Treat epoch numbers as values with units
A number such as 1776791100 cannot explain its own unit. An API might send seconds, milliseconds or microseconds since an epoch. Read the source contract and convert to seconds as needed before passing a POSIX timestamp to datetime.fromtimestamp(value, tz=timezone.utc). A wrong unit can produce a date far away from the expected period or raise an out-of-range error. Guessing from the number of digits can hide a bad record.
Check timestamp precision as well. When a system stores whole seconds, events within the same second may appear tied. If you need a total order, retain the sequence field defined by the source or use another justified tie-breaker. Printing more time digits does not recover detail lost during export.
Test dates that people get wrong
Add a leap-day example, an activity exactly at midnight, a date whose month and day could be swapped, and a missing date. If the system uses local datetime values, test one near a clock change. Write expected behavior as dates or instants before coding. When a conversion fails, retain the source value and the rule that it violated so a reviewer can distinguish bad data from a changed format.