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

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?



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Giulio Mattolin
Solution 2 DaSim
Solution 3