In this lesson, you will learn how to bridge the gap between human-readable date strings and machine-processable datetime objects using the strftime and strptime methods.
When working with data ingestion—like reading logs, CSV files, or API responses—dates arrive as strings. To perform arithmetic or sorting, you must convert these into formal datetime objects. Conversely, when presenting data to users, you must format these objects back into readable strings.
Formatting with strftime
The strftime (string format time) method allows you to define a template using format codes. For example, %Y represents a four-digit year, %m the month, and %d the day.
from datetime import datetime
now = datetime.now()
# Convert datetime object to a "Year-Month-Day" string
formatted_date = now.strftime("%Y-%m-%d")
print(formatted_date) # Output: e.g., "2023-10-27"
Parsing with strptime
The strptime (string parse time) method performs the inverse. It takes a raw string and a pattern, then constructs a datetime object. If the string structure doesn't match your pattern, Python will raise a ValueError, which acts as a helpful guardrail during data validation.
date_string = "27/10/2023 14:30"
# Parse a string into a datetime object
dt_object = datetime.strptime(date_string, "%d/%m/%Y %H:%M")
print(dt_object.year) # 2023
print(dt_object.minute) # 30
Why This Matters
Using these methods ensures that your data pipelines remain robust. By explicitly defining the format, you eliminate ambiguity between international date standards (e.g., DD/MM vs. MM/DD). Instead of relying on fragile string slicing or manual splitting to extract years or months, you let the datetime module handle the internal logic, giving you immediate access to robust attributes like .day, .weekday(), and full time-arithmetic capabilities.
Key Takeaway: Use strptime to interpret incoming date strings as machine-ready objects, and strftime to translate those objects back into the specific string format required for your output or reporting.