datetime.strptime() Explained
datetime.strptime() turns a date or time string into a real datetime object.
This is useful when your date comes from:
- user input
- a file
- a CSV
- an API response
- a log entry
The important rule is simple:
- the text must match the format string exactly
This page focuses on parsing strings into datetime objects. If you want to go the other way and turn a datetime object into text, see datetime.strftime() explained.
Quick example
from datetime import datetime
text = "2024-01-31 14:45"
dt = datetime.strptime(text, "%Y-%m-%d %H:%M")
print(dt)
print(type(dt))
Output:
2024-01-31 14:45:00
<class 'datetime.datetime'>
Use strptime() when you have a date as a string and need a real datetime object.
What datetime.strptime() does
datetime.strptime():
- converts a string into a
datetimeobject - reads the string using a format pattern
- requires the string and format to match exactly
A common use case is parsing dates from files, APIs, or user input before working with them in Python.
If you are new to the datetime module, see the Python datetime module overview.
Basic syntax
datetime.strptime(date_string, format)
Parts:
date_stringis the text you want to parseformattells Python how that text is arranged
It returns a datetime.datetime object.
Example:
from datetime import datetime
date_string = "2024-08-15"
dt = datetime.strptime(date_string, "%Y-%m-%d")
print(dt)
Output:
2024-08-15 00:00:00
Notice that the time becomes 00:00:00 if your string only contains a date.
A simple example
Here is a basic date string:
from datetime import datetime
text = "2024-08-15"
dt = datetime.strptime(text, "%Y-%m-%d")
print(dt)
Output:
2024-08-15 00:00:00
The format string is %Y-%m-%d.
That means:
%Y= 4-digit year%m= month number%d= day of month
So Python reads:
2024as the year08as the month15as the day
The dashes also matter. If your string uses /, your format must use / too.
Common format codes beginners need
These are the format codes most beginners use with strptime():
%Y= 4-digit year%y= 2-digit year%m= month as number%d= day of month%H= hour in 24-hour time%M= minute%S= second%I= hour in 12-hour time%p= AM or PM
You must also include separators exactly as they appear in the string, such as:
-/:- spaces
Example:
from datetime import datetime
text = "08/15/2024 09:30 PM"
dt = datetime.strptime(text, "%m/%d/%Y %I:%M %p")
print(dt)
Output:
2024-08-15 21:30:00
Matching the string to the format
When using strptime(), the string and format must match in three ways:
- the order must match
- the separators must match
- any extra text can cause an error
For example, if the string is:
"15/08/2024"
the correct format is:
"%d/%m/%Y"
not:
"%Y-%m-%d"
Compare these examples:
from datetime import datetime
text = "15/08/2024"
dt = datetime.strptime(text, "%d/%m/%Y")
print(dt)
Output:
2024-08-15 00:00:00
If you use the wrong format, Python raises a ValueError.
Parsing date and time together
You can parse both date and time in the same string.
A common pattern is:
%Y-%m-%d %H:%M:%S
Example:
from datetime import datetime
timestamp = "2024-08-15 16:45:30"
dt = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
print(dt)
print(dt.year)
print(dt.hour)
Output:
2024-08-15 16:45:30
2024
16
This is useful for:
- log files
- timestamps
- CSV data
- API responses
What errors beginners often see
The most common error is ValueError.
This usually means the string does not match the format string.
Example of code that causes an error:
from datetime import datetime
text = "2024/08/15"
dt = datetime.strptime(text, "%Y-%m-%d")
This fails because the string uses / but the format uses -.
Common causes:
- wrong separators
- wrong day-month-year order
- using
%mfor minutes by mistake - extra spaces or extra text in the string
- invalid dates such as
2024-02-30
Also watch out for this common mistake:
%m= month%M= minute
And this one:
%H= 24-hour clock%I= 12-hour clock, usually used with%p
If you want a broader explanation of this exception, see ValueError in Python: causes and fixes.
How to fix parsing problems
If strptime() is failing, check the string carefully.
Helpful steps:
- print the original string
- compare each part to each format code
- check spaces, commas, slashes, and dashes
- use
tryandexceptif the input may be invalid
Useful debugging commands:
print(date_string)
print(repr(date_string))
print(datetime.strptime('2024-08-15', '%Y-%m-%d'))
repr() is especially helpful because it shows hidden spaces.
Example with error handling:
from datetime import datetime
date_string = "2024-08-15"
try:
dt = datetime.strptime(date_string, "%Y-%m-%d")
print("Parsed:", dt)
except ValueError as e:
print("Could not parse date:", e)
Example with invalid input:
from datetime import datetime
date_string = "2024-02-30"
try:
dt = datetime.strptime(date_string, "%Y-%m-%d")
print("Parsed:", dt)
except ValueError as e:
print("Could not parse date:", e)
Output:
Could not parse date: day is out of range for month
strptime() vs strftime()
These two functions do opposite jobs.
strptime()parses a string into adatetimeobjectstrftime()formats adatetimeobject into a string
Example:
from datetime import datetime
text = "2024-08-15"
dt = datetime.strptime(text, "%Y-%m-%d")
formatted = dt.strftime("%d/%m/%Y")
print(dt)
print(formatted)
Output:
2024-08-15 00:00:00
15/08/2024
If you need output formatting, read datetime.strftime() explained.
Common mistakes
Beginners often run into the same parsing problems.
Here are the most common ones:
- using the wrong format code for the string
- mixing up
%m(month) and%M(minute) - using
%Hwith AM/PM instead of%Iwith%p - leaving extra spaces or text in the string
- using a date order that does not match the format string
- trying to parse invalid dates such as
2024-02-30
A good habit is to test with one known value first, then apply the same format to the rest of your data.
FAQ
What does datetime.strptime() return?
It returns a datetime.datetime object.
Why am I getting ValueError with strptime()?
Usually because the string does not exactly match the format string.
What is the difference between %m and %M?
%m is month. %M is minute.
Can strptime() parse both date and time?
Yes. You can include year, month, day, hour, minute, and second format codes.
What is the difference between strptime() and strftime()?
strptime() reads a string into a datetime object. strftime() turns a datetime object into a string.