How to Parse a String to a Datetime in Python (strptime)
Learn how to convert strings to datetime objects in Python. Master the strptime method, parse date strings, handle timezones, and prevent format errors.
Explanation
When building applications that process user form submissions, scrape web databases, parse server logs, or import CSV sheets, you will frequently receive date and time information as raw text strings (e.g., `"2026-05-25 15:45"`). Since you cannot perform calculations, date arithmetic, or sorting on strings, you must parse them into Python datetime objects.
The primary method for this conversion is `datetime.strptime(date_string, format_string)`. The name stands for "string parse time". The function takes the raw date string and a format template containing directives (like `%Y` for year, `%m` for month, and `%d` for day) and returns a corresponding datetime object.
If the input string does not match the provided format template exactly, Python raises a `ValueError`. To prevent crashes, always wrap `strptime()` operations in a `try-except` block. For applications parsing diverse, unstructured date inputs, external libraries like `python-dateutil` can help automate parser detection.
Step-by-Step Implementation
- 1
Import the datetime class from the datetime module.
- 2
Identify the exact structure of your date string (e.g., day, month, separators).
- 3
Call datetime.strptime(date_string, format_pattern) with appropriate directives (like %Y, %m, %d).
- 4
Wrap the parsing statement in a try-except ValueError block to handle malformed strings gracefully.
Code Example
This script demonstrates parsing date strings using datetime.strptime, handling invalid inputs, and calculating date differences.
from datetime import datetime
# 1. Basic parsing using strptime
date_str = "2026-05-25 18:30:00"
format_template = "%Y-%m-%d %H:%M:%S"
parsed_date = datetime.strptime(date_str, format_template)
print("Parsed DateTime:", parsed_date)
print("Month parsed:", parsed_date.month)
print("Hour parsed:", parsed_date.hour)
# 2. Handling parse errors safely
bad_date_str = "25/05/2026"
try:
datetime.strptime(bad_date_str, "%Y-%m-%d")
except ValueError as e:
print(f"\nParse Error: {e}")
# Correcting the format
corrected_date = datetime.strptime(bad_date_str, "%d/%m/%Y")
print("Corrected Parse:", corrected_date.date())Parsed DateTime: 2026-05-25 18:30:00
Month parsed: 5
Hour parsed: 18
Parse Error: time data '25/05/2026' does not match format '%Y-%m-%d'
Corrected Parse: 2026-05-25Frequently Asked Questions
What is the difference between strftime and strptime?
strptime (string parse time) parses a string to create a datetime object. strftime (string format time) formats a datetime object into a readable string representation.
How do I parse ISO 8601 date strings (e.g., "2026-05-25T18:30:00Z")?
In Python 3.7+, you can use the built-in datetime.fromisoformat(string) function, which handles ISO strings efficiently without requiring a manual format template.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Strings
Master string manipulation in Python. Learn string methods, slicing, concatenation, and formatting techniques with clear, executable code examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.