Search code examples
djangopython-datetime

how to change two dates to number of days and hours jango


i'm trying to change two dates check_in and check_out to days and hours

my models.py

check_in = models.DateTimeField(default=datetime.now)
check_out = models.DateTimeField()

i tried this

check_in_date = obj.check_in
check_out_date = obj.check_out
days = check_out_date - check_in_date 
day = days.days
hour = days.seconds / 60

for the day it works as i expect except that when i select this two dates check_in=05-07-2021 04:46 PM to check_out=05-07-2021 10:46 PM i want to show 0 days 6 hours but it show 0 days 360.0 hours ! is it possible to return such date format


Solution

  • You need subtract check_in_date from check_out_date, furthemore you should divide the seconds by 3600, not 60. We can implement this with:

    check_in_date = obj.check_in
    check_out_date = obj.check_out
    days = check_out_date - check_in_date
    day = days.days
    hour = days.seconds // 3600