2

I'm trying to convert a string date_str = '01-01-2000' to a date object, and want to compare with a given date.

I used my_date = datetime.datetime.strptime(date_str, "%d-%m-%Y") which works, until I try to compare with a given date:

    if my_date <= other_date:
TypeError: can't compare datetime.datetime to datetime.date

When I change datetime to date and do datetime.date.strptime(date_str, "%d-%m-%Y"), I get AttributeError: type object 'datetime.date' has no attribute 'strptime':

datetime.date.strptime(date_str, "%d-%m-%Y")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: type object 'datetime.date' has no attribute 'strptime'

2 Answers 2

4

There indeed is no strptime() for a datetime.date object, and there is no strpdate() function either.

Just use datetime.strptime() and convert to a date object afterwards:

my_date = datetime.datetime.strptime(date_str, "%d-%m-%Y").date()
Sign up to request clarification or add additional context in comments.

Comments

0

I've added support for this in Python 3.14:

$ python -V
Python 3.14.0
>>> from datetime import date
>>> date.strptime("01-01-2000", "%d-%m-%Y")
datetime.date(2000, 1, 1)

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.