set datetime object time value to 0

I need to set the time value of detatime objects to 00:00, so I can easily compare two ‘dates’

Now I do:

extracted_start_date = datetime.strptime(extracted_start_date.strftime('%Y-%m-%d'), '%Y-%m-%d')

so I have my datetime object

$ datetime.datetime(2021, 3, 18, 11, 13, 53, 782088), 

I extract the date string strftime(‘%Y-%m-%d’)

$ '2021-03-18'

and put this back into a datetime object now wch has time 00:00

$ datetime.datetime(2021, 3, 18, 0, 0)

This seems quite elaborate, is there a more efficient way, or is it OK like this?

Answer

datetime.datetime objects have method date which return datetime.date instance and these might be used for day-based comparison, consider following example:

import datetime
d1 = datetime.datetime(2021, 3, 17, 9, 0, 0)  # yesterday 9:00
d2 = datetime.datetime(2021, 3, 18, 9, 0, 0)  # today 9:00
d3 = datetime.datetime(2021, 3, 18, 12, 0, 0) # today 12:00
print(d1.date() == d2.date())
print(d2.date() == d3.date())

output:

False
True

Leave a Reply

Your email address will not be published. Required fields are marked *