ValueError: time data 'X' does not match format '%Y-%m-%d' | bobbyhadz (2024)

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

  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: time data 'X' does not match format '%Y-%m-%d' | bobbyhadz (1)

# 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

ValueError: time data 'X' does not match format '%Y-%m-%d' | bobbyhadz (2)

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

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

ValueError: time data 'X' does not match format '%Y-%m-%d' | bobbyhadz (3)

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

ValueError: time data 'X' does not match format '%Y-%m-%d' | bobbyhadz (4)

# 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

ValueError: time data 'X' does not match format '%Y-%m-%d' | bobbyhadz (5)

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:

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

  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 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
ValueError: time data 'X' does not match format '%Y-%m-%d' | bobbyhadz (2024)
Top Articles
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 6642

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.