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

Time:02-11

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related