5

I just tried to display my birthday(dd/mm/yyyy). And then, I got "ValueError" which is like "time data %r does not match format %r" % and "time data ' 01/27/1998' does not match format '%d/%m/%y'"

Here is my code

from datetime import datetime, timedelta

birthday = input('When is your birthday (dd/mm/yyyy)?')

birthday_date = datetime.strptime(birthday, "%d/%m/%y")

print('Birthday : ' + str(birthday_date))

one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print('Day before birthday : ' + str(birthday_eve))

This is the detail of error

When is your birthday (dd/mm/yyyy)? 01/27/1998
Traceback (most recent call last):
  File "010-input_date.py", line 5, in <module>
    birthday_date = datetime.strptime(birthday, "%d/%m/%y")
  File 
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py", 
line 568,
in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File 
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py", 
line 349,
in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data ' 01/27/1998' does not match format '%d/%m/%y'

3 Answers3

6

It has to be, '%d/%m/%Y', so replace the following line:

birthday_date = datetime.strptime(birthday, "%d/%m/%y")

With:

birthday_date = datetime.strptime(birthday, "%d/%m/%Y")
U11-Forward
  • 41,703
  • 9
  • 50
  • 73
2

From your traceback it looks like you have a little bit of whitespace there. The golden rule is: always clean user input.

birthday_date = datetime.strptime(birthday.strip(), "%d/%m/%y")

Remove the whitespace and all is well.

Also %y only matches 2 digits. If you want to match 4 it's %Y

Sheena
  • 13,328
  • 11
  • 65
  • 103
0

Well, you specify dd/mm/yyyy, but you fed in 01/27/1998 which is mm/dd/yyyy:

birthday_date = datetime.strptime(birthday, "%m/%d/%Y")  # fixed

Also note that %Y matches a 4-digit year while %y only matches the last 2 digits. (Reference link)

xjcl
  • 5,491
  • 3
  • 32
  • 42