Home > Software design >  ValueError: time data 'test_str' does not match format '%m/%d/%Y'
ValueError: time data 'test_str' does not match format '%m/%d/%Y'

Time:11-08

Traceback (most recent call last):
  File "C:\pythoneg\q2.py", line 8, in <module>
    print(datetime.datetime.strptime("test_str", "%m/%d/%Y").strftime("%Y-%m-%d") )
    raise ValueError("time data %r does not match format %r" %
I tried to read the user entered date as the input and display it in the format as i desire
    import datetime
    test_str=input("Enter date")
    format= "%m/%d/%Y"
    try :
    res= bool(datetime.strptime(test_str,format))   
    except:
    print("The Date is not in the required format" )
    print(datetime.datetime.strptime("test_str", "%m/%d/%Y").strftime("%Y-%m-%d") )

I was expecting it yo give the date in the desired format

CodePudding user response:

You have to make an input in the same format "%m/%d/%Y", otherwise it wont work.

Try it:

import datetime
test_str=input("Enter date")
format= "%m/%d/%Y"
try :
    res= bool(datetime.strptime(test_str,format))   
    print(datetime.datetime.strptime("test_str", "%m/%d/%Y").strftime("%Y-%m-%d") )
except:
    print("The Date is not in the required format" )
  • Related