I have a date stored in a text file in this format "19 May 2021"
, I want to compare this date to the today’s date to see if we have reached this date or not (> / <) comparisons. I was instructed to first convert this string date to a date object, I am failing to do so.
For overdue_tasks in task_overview:
JavaScript
x
8
1
# Iterating through the file
2
from datetime import date as dt
3
4
overdue_tasks = overdue_tasks.split(", ")
5
dates = overdue_tasks[4] # This date is found in this index
6
date_obj = dt.strptime(dates, "%d %b %Y")
7
print(date_obj) # Trying to see if the date did convert
8
This is the error I get:
JavaScript
1
5
1
line 27, in <module>
2
date_obj = dt.strptime(dates, "%m %d %y")
3
AttributeError:
4
type object 'datetime.date' has no attribute 'strptime'
5
Advertisement
Answer
The strptime()
method is from datetime.datetime
, not datetime.time
. See the documentation for datetime.datetime.strptime()
.
So you’ll simply need to change
JavaScript
1
2
1
from datetime import date as dt
2
to
JavaScript
1
2
1
from datetime import datetime as dt
2