Alfred
Alfred

Reputation: 570

Number of dates between two dates

I would like to get the number of days between two dates. But the days does not have to be full 24-hour days. If the first date is right before midnight and the second date is right after midnight, I still want it to count as one day.

from datetime import datetime
a = datetime.strptime("2021-07-13 22:00:00", "%Y-%m-%d %H:%M:%S")
b = datetime.strptime("2021-07-14 06:00:00", "%Y-%m-%d %H:%M:%S")

print((b-a).days)

# Output: 0
# Expected output: 1

Upvotes: 4

Views: 103

Answers (1)

oskros
oskros

Reputation: 3305

Just remove the time component of the datetime by calling .date(),

from datetime import datetime
a = datetime.strptime("2021-07-13 22:00:00", "%Y-%m-%d %H:%M:%S").date()
b = datetime.strptime("2021-07-14 06:00:00", "%Y-%m-%d %H:%M:%S").date()

print((b-a).days)

Upvotes: 7

Related Questions