Last updated: Apr 10, 2024
Reading timeยท5 min
The error "ValueError: time data 'X' does not match format '%Y-%m-%d'" most commonly occurs when:
datetime.strptime()
method.y
when formatting (which represents a 2-digit year).strptime()
.Here is an example of how the error occurs.
from datetime import datetime my_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 up
the 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.
The solution, in this case, would be to specify a second argument of %Y-%d-%m
.
from datetime import datetime my_str = '2023-24-09' # ๐๏ธ YYYY-DD-MM date = datetime.strptime(my_str, '%Y-%d-%m') print(date) # ๐๏ธ 2023-09-24 00:00:00
datetime.strptime()
method.y
directive means 2-digit yearAnother common cause of the error is using the lowercase y
directive which
means 2-digit year (e.g. 23) instead of the uppercase Y
directive which means
4-digit year (e.g. 2023).
from datetime import datetime my_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.
from datetime import datetime my_str = '2023-24-09' # โ Using uppercase Y directive date = datetime.strptime(my_str, '%Y-%d-%m') print(date) # ๐๏ธ 2023-09-24 00:00:00
You can check the meaning of all of the directives in this table in the official docs.
Another common cause of the error is specifying incorrect separators.
import datetime # ๐๏ธ Forward slashes my_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 the
day, month and year, however, we used hyphens in the second argument we passed
to strptime()
.
To solve the error, make sure the format matches by using forward slashes in the format string as well.
import datetime my_str = "21/11/2023 09:30" # โ Format now matches dt = datetime.datetime.strptime( my_str, "%d/%m/%Y %H:%M" ) print(dt) # ๐๏ธ 2023-11-21 09:30:00
Here is a working example of including the seconds and microseconds as well.
import datetime my_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 the separators for the hours, minutes and seconds are colons in the example.
You can use this table from the docs to look at the different directives and their meaning.
The
datetime.strptime()
method returns a datetime
object that corresponds to the provided date string,
parsed according to the format.
from datetime import datetime d = '2022-11-24 09:30:00.000123' # ๐๏ธ Convert string to datetime object datetime_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:30AM print(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 out
this table
of the official docs.
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
.
import pandas as pd df = pd.read_csv('employees.csv', sep=',', encoding='utf-8') # first_name last_name # 0 Alice Smith # 1 Bobby Hadz # 2 Carl Smith print(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.014000 print(df)
The code sample assumes that you have an employees.csv
file in the same
directory as your main.py
file.
first_name,last_name,date Alice,Smith,01/21/1995 14:32:44.042010 Bobby,Hadz,04/14/1998 12:51:42.014000
When the
infer_datetime_format
argument is set to True
, pandas
attempts to infer the format of the
datetime
strings in the columns.
python-dateutil
module insteadAn alternative you can try is the python-dateutil module.
First, install the module by running the following command.
pip install python-dateutil # ๐๏ธ for Python 3 pip3 install python-dateutil # ๐๏ธ If you don't have pip in your PATH environment variable python -m pip install python-dateutil python3 -m pip install python-dateutil py -m pip install python-dateutil # ๐๏ธ If you get a permissions error pip install python-dateutil --user # ๐๏ธ For Anaconda conda install -c anaconda python-dateutil
Now import the module and use it to parse a date and time string.
from dateutil import parser dt_string = '20 November, 2023, 3:25:36, pm' # ๐๏ธ 2023-11-20 15:25:36 print(parser.parse(dt_string))
The parser.parse()
method parses a string and returns a datetime
object.
To solve the error "ValueError: time data 'X' does not match format '%Y-%m-%d'", make sure:
datetime.strptime()
method.You can learn more about the related topics by checking out the following tutorials: