Skip to main content

Date Formatting & Parsing: strftime() & strptime()

When interacting with users, databases, or APIs, dates are passed back and forth as text strings (e.g., "08-Aug-2026" or "2026/08/08 14:30:00").

Python provides two essential methods for date conversion:

  1. strftime() (String Format Time): Converts a datetime object into a readable text string.
  2. strptime() (String Parse Time): Converts a raw text string back into a Python datetime object.
Easy Mnemonic
  • f in strftime stands for Format (Output to String).
  • p in strptime stands for Parse (Input from String).

1. Converting Dates to Strings with strftime()

from datetime import datetime

now = datetime.now()

# Format 1: Standard YYYY-MM-DD
print(now.strftime("%Y-%m-%d")) # Output: 2026-08-08

# Format 2: Readable format (e.g. 08 August 2026)
print(now.strftime("%d %B %Y")) # Output: 08 August 2026

# Format 3: Time format (12-hour format with AM/PM)
print(now.strftime("%I:%M %p")) # Output: 01:45 PM

# Format 4: Complete timestamp with weekday
print(now.strftime("%A, %b %d, %Y - %H:%M:%S"))
# Output: Saturday, Aug 08, 2026 - 13:45:10

2. Essential Format Codes Cheatsheet

CodeMeaningExample Output
%Y4-Digit Year2026
%y2-Digit Short Year26
%m2-Digit Month Number08
%BFull Month NameAugust
%bShort Month NameAug
%dDay of Month (01-31)08
%AFull Weekday NameSaturday
%aShort Weekday NameSat
%H24-Hour Clock (00-23)14
%I12-Hour Clock (01-12)02
%MMinutes (00-59)30
%SSeconds (00-59)45
%pAM / PM markerPM

3. Parsing Raw Text into Dates with strptime()

When receiving raw date strings from API JSON payloads or user input forms, use strptime() with the exact matching format template:

from datetime import datetime

raw_input_1 = "25/12/2026"
date_obj_1 = datetime.strptime(raw_input_1, "%d/%m/%Y")
print("Parsed Date:", date_obj_1.year) # Output: Parsed Date: 2026

raw_input_2 = "2026-Aug-15 09:30 AM"
date_obj_2 = datetime.strptime(raw_input_2, "%Y-%b-%d %I:%M %p")
print("Parsed Month:", date_obj_2.month) # Output: Parsed Month: 8

Quick Summary

  • strftime(format) (String From Time): Converts datetime objects into formatted custom text strings (e.g., %Y-%m-%d).
  • strptime(str, format) (String Parse Time): Parses raw strings from APIs or forms into Python datetime objects.
  • Core Format Codes: %Y (4-digit year), %m (month number), %B (month name), %d (day), %H (24h) / %I (12h), %M (minute), %p (AM/PM).

What's Next?

Let's look at hardware timers, rate-limiting delays, and precision performance benchmarking with the time module!