Parsing and Formatting Dates
16 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Dates reach a program as text: a form field, a file column, a log line. They must become real dates to be compared, and become text again to be shown. Two methods do this, and a few format codes drive both.
strftime: date to text
Format code is a short marker such as %Y or %d inside a format string. strftime and strptime replace or read it as that part of a date.
strftime(format) builds text from a date. The format mixes codes with plain characters: %Y year, %m month number, %d day, %B month name, %b short name, %A weekday name, %H hour, %M minute, %S second.
from datetime import date
d = date(2026, 11, 8)print(d.strftime("%d %b %Y"))print(d.strftime("%A, %d %B %Y"))Example 1 · Format one date many ways
from datetime import datetime
stamp = datetime(2026, 11, 8, 15, 5)for fmt in ["%Y-%m-%d", "%d/%m/%Y", "%d %b %Y", "%A, %d %B %Y", "%I:%M %p"]: print(stamp.strftime(fmt))2026-11-08 08/11/2026 08 Nov 2026 Sunday, 08 November 2026 03:05 PM
What this code does
- Each format picks different codes from the same datetime.
%I:%M %pis a 12-hour clock with AM or PM.
Remember %m is the month and %M is the minute. Mixing them up is a very common bug.
strptime: text to datetime
datetime.strptime(text, format) reads text into a datetime. The format must describe the text exactly, so "08/11/2026" needs "%d/%m/%Y". Use .date() when you only want the date part.
from datetime import datetime
d = datetime.strptime("08/11/2026", "%d/%m/%Y").date()print(d)Example 2 · Parse text into dates
from datetime import datetime
d1 = datetime.strptime("08/11/2026", "%d/%m/%Y")d2 = datetime.strptime("2026-11-08 14:30", "%Y-%m-%d %H:%M")print(d1)print(d2.strftime("%A"))print(d2 - d1)2026-11-08 00:00:00 Sunday 14:30:00
What this code does
- The format has to match the text, character for character.
- Once parsed, the values are real datetimes, so subtraction works.
If the text does not fit the format, strptime raises ValueError.
ISO 8601: the safe text format
ISO 8601 is the international standard for writing dates and times, such as 2026-11-08 or 2026-11-08T09:30:00. It is unambiguous and sorts correctly as plain text.
ISO 8601 writes a date as 2026-11-08 and a datetime as 2026-11-08T09:30:00. It is unambiguous and sorts correctly as plain text. isoformat() writes it and fromisoformat() reads it, with no format string.
from datetime import date, datetime
print(datetime(2026, 11, 8, 9, 30).isoformat())print(date.fromisoformat("2026-11-08").year)Example 3 · ISO text round trip
from datetime import date, datetime
stamp = datetime(2026, 11, 8, 9, 30)text = stamp.isoformat()print(text)print(datetime.fromisoformat(text) == stamp)print(sorted(["2026-11-08", "2026-02-15", "2025-12-31"]))print(date.fromisoformat("2026-02-15").month)2026-11-08T09:30:00 True ['2025-12-31', '2026-02-15', '2026-11-08'] 2
What this code does
isoformatandfromisoformatare exact opposites.- ISO dates sort in the right order even as plain text.
Use ISO text when you store dates in files, JSON or databases.
Bad input and ambiguous dates
03/04/2026 is 3 April in one country and 4 March in another. Pick one format and state it. Wrap parsing in try and except ValueError, and never let one bad row crash the whole file.
from datetime import datetime
try: datetime.strptime("31/02/2026", "%d/%m/%Y")except ValueError: print("not a real date")Example 4 · Try several formats
from datetime import datetime
def parse_date(text): for fmt in ("%Y-%m-%d", "%d/%m/%Y"): try: return datetime.strptime(text, fmt).date() except ValueError: pass return None
for text in ["2026-11-08", "09/11/2026", "bad", "31/02/2026"]: print(text, "->", parse_date(text))2026-11-08 -> 2026-11-08 09/11/2026 -> 2026-11-09 bad -> None 31/02/2026 -> None
What this code does
- Each format is tried in turn. A wrong format raises
ValueError, which we catch and skip. - Text that fits none, or is not a real date, gives
None.
Python also rejects dates that do not exist, such as 31 February.
Next step
Check your understanding
11 quick questions