Home > OS >  Modify days counter on datetime [Python]
Modify days counter on datetime [Python]

Time:11-05

I have this code and I want to count the days between 2 dates.

from datetime import date, datetime

checkin= datetime(2022, 1, 30, 1, 15, 00)
checkout= datetime(2022, 1, 31, 0, 0, 00)
count_days= (checkout - checkin).days

In this case, the result of count_days result is 0, because in an operation with 2 datetimes, it takes into account hours, minutes and seconds.

I want the result to be 1 because is 1 day of difference. Type of variables must be datetimes. Thanks!

CodePudding user response:

Convert them to dates first, with the date method.

from datetime import date, datetime

checkin = datetime(2022, 1, 30, 1, 15, 00)
checkout = datetime(2022, 1, 31, 0, 0, 00)
count_days = (checkout.date() - checkin.date()).days

CodePudding user response:

Could you do something like this?

(assuming you want a minimum since the solution you have is similar)

from datetime import date, datetime

check_in= datetime(2022, 1, 30, 1, 15, 00)
check_out= datetime(2022, 1, 31, 0, 0, 00)

# Number of days between two dates (min 1 day)
days = (check_out - check_in).days   1

print(days)
  • Related