ValueError: time data 'X' does not match format '%Y-%m-%d'

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
5 min

banner

# ValueError: time data 'X' does not match format '%Y-%m-%d'

The error "ValueError: time data 'X' does not match format '%Y-%m-%d'" most commonly occurs when:

  1. There is a formatting issue when calling the datetime.strptime() method.
  2. The places for the month and the day of the month have been switched.
  3. Using a lowercase y when formatting (which represents a 2-digit year).
  4. Using incorrect separators in the call to strptime().

valueerror timedata does not match format

# Swapping the places of the month and day directives

Here is an example of how the error occurs.

main.py
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.

# 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
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

use correct format for second argument

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 which means 2-digit year (e.g. 23) instead of the uppercase Y directive which means 4-digit year (e.g. 2023).

main.py
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.

main.py
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

use uppercase y directive

The code for this article is available on GitHub

You can check the meaning of all of the directives in this table in the official docs.

# Specifying incorrect separators in the format string

Another common cause of the error is specifying incorrect separators.

main.py
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.

main.py
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

format should match datetime string

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
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

include seconds and microseconds in format string

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.

Everything matches between the date and time string and the format string, so no error is raised.

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.

main.py
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:

NameDescription
date_stringThe date string that is to be converted to a datetime object
formatThe 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.

# 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
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.

employees.csv
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.

# Using the python-dateutil module instead

An alternative you can try is the python-dateutil module.

First, install the module by running the following command.

shell
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.

main.py
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 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:

  1. There aren't any formatting issues when calling the datetime.strptime() method.
  2. The places for the month and the day of the month have not been switched.
  3. You are using the correct directive for the year.
  4. You are using the correct separators in the format string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev