SyntaxStudy
Sign Up
Python Formatting and Parsing Dates
Python Beginner 3 min read

Formatting and Parsing Dates

strftime and strptime

strftime formats a datetime as a string. strptime parses a string into a datetime using a format code.

Example
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")   # "2024-06-15 14:30:00"
iso = now.isoformat()                             # "2024-06-15T14:30:00"
parsed = datetime.strptime("15/06/2024", "%d/%m/%Y")
print(formatted, iso, parsed)
Pro Tip

isoformat() is the safest portable format — use it for APIs and storage.