# ValueError: time data 'X' does not match format '%Y-%m-%d'
The error "ValueError: time data 'X' does not match format '%Y-%m-%d'" mostcommonly occurs when:
- There is a formatting issue when calling the
datetime.strptime()
method. - The places for the month and the day of the month have been switched.
- Using a lowercase
y
when formatting (which represents a 2-digit year). - Using incorrect separators in the call to
strptime()
.
# Swapping the places of the month and day directives
Here is an example of how the error occurs.
main.py
Copied!
from datetime import datetimemy_str = '2023-24-09' # ๐๏ธ YYYY-DD-MM# โ๏ธ ValueError: time data '2023-24-09' does not match format '%Y-%m-%d'date = datetime.strptime(my_str, '%Y-%m-%d')
Notice that the date string is formatted as YYYY-DD-MM
, but we have mixed upthe places of the %m
and %d
directives in the call to datetime.strptime()
.
The month can't possibly be 24
, so the error is raised.
# Using a correct format for the second argument
The solution, in this case, would be to specify a second argument of %Y-%d-%m
.
main.py
Copied!
from datetime import datetimemy_str = '2023-24-09' # ๐๏ธ YYYY-DD-MMdate = datetime.strptime(my_str, '%Y-%d-%m')print(date) # ๐๏ธ 2023-09-24 00:00:00
The code for this article is available on GitHub
The date string now corresponds to the format we passed to the datetime.strptime()
method.
# The lowercase y
directive means 2-digit year
Another common cause of the error is using the lowercase y
directive whichmeans 2-digit year (e.g. 23) instead of the uppercase Y
directive which means4-digit year (e.g. 2023).
main.py
Copied!
from datetime import datetimemy_str = '2023-24-09'# โ๏ธ ValueError: time data '2023-24-09' does not match format '%y-%d-%m'date = datetime.strptime(my_str, '%y-%d-%m')
The year in the example contains 4 digits, so we have to use an uppercase Y
directive.
main.py
Copied!
from datetime import datetimemy_str = '2023-24-09'# โ Using uppercase Y directivedate = datetime.strptime(my_str, '%Y-%d-%m')print(date) # ๐๏ธ 2023-09-24 00:00:00
The code for this article is available on GitHub
You can check the meaning of all of the directives inthis tablein the official docs.
# Specifying incorrect separators in the format string
Another common cause of the error is specifying incorrect separators.
main.py
Copied!
import datetime# ๐๏ธ Forward slashesmy_str = "21/11/2023 09:30"# ๐๏ธ Hyphen separators# โ๏ธ ValueError: time data '21/11/2023 09:30' does not match format '%d-%m-%Y %H:%M'dt = datetime.datetime.strptime( my_str, "%d-%m-%Y %H:%M")
Note that the date and time string uses forward slashes as separators for theday, month and year, however, we used hyphens in the second argument we passedto strptime()
.
To solve the error, make sure the format matches by using forward slashes in theformat string as well.
main.py
Copied!
import datetimemy_str = "21/11/2023 09:30"# โ Format now matchesdt = datetime.datetime.strptime( my_str, "%d/%m/%Y %H:%M")print(dt) # ๐๏ธ 2023-11-21 09:30:00
The code for this article is available on GitHub
# Including the Seconds and Microseconds in the format string
Here is a working example of including the seconds and microseconds as well.
main.py
Copied!
import datetimemy_str = "21/11/2023 09:30:28.087"dt = datetime.datetime.strptime( my_str, "%d/%m/%Y %H:%M:%S.%f")print(dt) # ๐๏ธ 2023-11-21 09:30:28.087000
The separators for the days, months and years are forward slashes and theseparators for the hours, minutes and seconds are colons in the example.
Everything matches between the date and time string and the format string, so no error is raised.
You can usethis tablefrom the docs to look at the different directives and their meaning.
Thedatetime.strptime()method returns a datetime
object that corresponds to the provided date string,parsed according to the format.
main.py
Copied!
from datetime import datetimed = '2022-11-24 09:30:00.000123'# ๐๏ธ Convert string to datetime objectdatetime_obj = datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f')print(datetime_obj) # ๐๏ธ 2022-11-24 09:30:00.000123# ๐๏ธ Thursday, 24. November 2022 09:30AMprint(datetime_obj.strftime("%A, %d. %B %Y %I:%M%p"))
The strptime()
method takes the following 2 arguments:
Name | Description |
---|---|
date_string | The date string that is to be converted to a datetime object |
format | The format string that should be used to parse the date string into a datetime object |
For a complete list of the format codes that the strptime
method supports,check outthis tableof the official docs.
# Setting infer_datetime_format
to True
if you use pandas
If you use the pandas
module to read a CSV file that contains date columns,try setting the infer_datetime_format
keyword argument to True
.
main.py
Copied!
import pandas as pddf = pd.read_csv('employees.csv', sep=',', encoding='utf-8')# first_name last_name# 0 Alice Smith# 1 Bobby Hadz# 2 Carl Smithprint(df)print('-' * 50)df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)# first_name last_name date# 0 Alice Smith 1995-01-21 14:32:44.042010# 1 Bobby Hadz 1998-04-14 12:51:42.014000print(df)
The code sample assumes that you have an employees.csv
file in the samedirectory as your main.py
file.
employees.csv
Copied!
first_name,last_name,dateAlice,Smith,01/21/1995 14:32:44.042010Bobby,Hadz,04/14/1998 12:51:42.014000
When theinfer_datetime_formatargument is set to True
, pandas
attempts to infer the format of thedatetime
strings in the columns.
# Using the python-dateutil
module instead
An alternative you can try is thepython-dateutil module.
First, install the module by running the following command.
shell
Copied!
pip install python-dateutil# ๐๏ธ for Python 3pip3 install python-dateutil# ๐๏ธ If you don't have pip in your PATH environment variablepython -m pip install python-dateutilpython3 -m pip install python-dateutilpy -m pip install python-dateutil# ๐๏ธ If you get a permissions errorpip install python-dateutil --user# ๐๏ธ For Anacondaconda install -c anaconda python-dateutil
Now import the module and use it to parse a date and time string.
main.py
Copied!
from dateutil import parserdt_string = '20 November, 2023, 3:25:36, pm'# ๐๏ธ 2023-11-20 15:25:36print(parser.parse(dt_string))
The code for this article is available on GitHub
The parser.parse()
method parses a string and returns a datetime
object.
# Conclusion
To solve the error "ValueError: time data 'X' does not match format'%Y-%m-%d'", make sure:
- There aren't any formatting issues when calling the
datetime.strptime()
method. - The places for the month and the day of the month have not been switched.
- You are using the correct directive for the year.
- You are using the correct separators in the format string.
# Additional Resources
You can learn more about the related topics by checking out the followingtutorials:
- Check if a variable is a Datetime object in Python
- How to add Hours to Datetime in Python
- How to add Minutes to Datetime in Python
- How to add Seconds to Datetime in Python
- AttributeError module 'datetime' has no attribute 'strptime'
- NameError: name 'time' or 'datetime' is not defined in Python
- How to change the Port and Host in a Flask application
- Python socket.error: [Errno 104] Connection reset by peer
- How to draw empty circles on a Scatter Plot in Matplotlib
- Convert an Image to a Base64-encoded String in Python
- Pandas: Out of bounds nanosecond timestamp [Solved]
- How to get a Quarter from a Date in Pandas [4 Ways]
- How to format datetime or time as AM/PM in Python