Time data does not match format YYYY-MM-DD

998 views django

I have an issue getting the difference in days between 2 dates in python.

I have the following block of code:

    last_used = models.DateTimeField(default=datetime.now().date(), editable=False)
    date_format = "%y-%m-%d"
    a = datetime.strptime(str(datetime.now().date()), date_format)
    b = datetime.strptime(str(last_used), date_format)
    days_since_use = models.IntegerField(default=(b-a).days, editable=False)

I have tried with both the %y-%m-%d and YYYY-MM-DD formats but neither worked.

ValueError: time data '2018-09-16' does not match format '%y-%m-%d'

Any ideas?

answered question

1 Answer


The year with century (as in 2018, not 18) is denoted with %Y (so an uppercase Y) per documentation.

The format is thus:


With this format, the datetime.strptime function yields the following result:

>>> datetime.strptime('2018-09-16', '%y-%m-%d')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data '2018-09-16' does not match format '%y-%m-%d'
>>> datetime.strptime('2018-09-16', '%Y-%m-%d')
datetime.datetime(2018, 9, 16, 0, 0)

posted this

Have an answer?


Please login first before posting an answer.