ValueError: time data '02/03/2022' does not match format '%d/%m/%y '

Question:

How to return values only within a specific date range?

I am new to python

My code is:

for report_date in REPORT_DATE_TYPES:
    if report_date in result:
        date = result[report_date].split(' ')[0]
        date = datetime.strptime(date, '%d/%m/%y ')

but I am getting an error:

raise ValueError("time data %r does not match format %r" %
ValueError: time data '02/03/2022' does not match format '%d/%m/%y '

How to fix this?

Answers:

To point out the year you need to use %Y and also there is an additional space at the end of the format you gave that it’s not present in the date. Try with date = datetime.strptime(date, '%d/%m/%Y')

Answered By: Giulio Mattolin

The %y refers to just the last 2 digit of the year, not the whole year as you have in the example.

20/03/21 is in format '%d/%m/%y while
20/03/2021 is in format '%d/%m/%Y(note the capital Y) therefore you just need to update the code as following

for report_date in REPORT_DATE_TYPES:
   if report_date in result:
       date = result[report_date].split(' ')[0]
       date = datetime.strptime(date, '%d/%m/%Y ')

You can find an useful table of each flag on this link

Answered By: DaSim

This error indicates that format and input are not aligned.
In this example the input: ’02/03/2022′,
does not match format ‘%d/%m/%y’

Why?
Since %y is a year with two letter, such as ’22’ rather than ‘2022’.
BTW, the rest of the input does match the format.

Use this link to verify the format in correct:
https://www.geeksforgeeks.org/python-datetime-strptime-function/

Answered By: Nir Kahila
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.