calculate difference between two time in hour

11,731

Solution 1

Since i.inTime and i.outTime are time objects you cannot simply subtract them. A good approach is to convert them to datetime adding the date part (use today() but it is irrelevant to the difference), then subtract obtaining a timedelta object.

delta = datetime.combine(date.today(), i.outTime) - datetime.combine(date.today(), i.inTime)

(Look here: subtract two times in python)

Then if you want to express delta in hours:

delta_hours = delta.days * 24 + delta.seconds / 3600.0

A timedelta object has 3 properties representing 3 different resolutions for time differences (days, seconds and microseconds). In the last expression I avoided to add the microseconds but I suppose it is not relevant in your case. If it is also add delta.microseconds / 3600000000.0 Note that simply dividing seconds by 3600 would have returned only the integer part of hours avoiding fractions. It depends on your business rules how to round it up (round, floor, ceil or leave the fractional part as I did)

Solution 2

You might want to play with this codes:

from datetime import datetime

#set the date and time format
date_format = "%m-%d-%Y %H:%M:%S"

#convert string to actual date and time
time1  = datetime.strptime('8-01-2008 00:00:00', date_format)
time2  = datetime.strptime('8-02-2008 01:30:00', date_format)

#find the difference between two dates
diff = time2 - time1


''' days and overall hours between two dates '''
print ('Days & Overall hours from the above two dates')
#print days
days = diff.days
print (str(days) + ' day(s)')

#print overall hours
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = days_to_hours + diff_btw_two_times
print (str(overall_hours) + ' hours');



''' now print only the time difference '''
''' between two times (date is ignored) '''

print ('\nTime difference between two times (date is not considered)')

#like days there is no hours in python
#but it has seconds, finding hours from seconds is easy
#just divide it by 3600

hours = (diff.seconds) / 3600  
print (str(hours) + ' Hours')


#same for minutes just divide the seconds by 60

minutes = (diff.seconds) / 60
print (str(minutes) + ' Minutes')

#to print seconds, you know already ;)

print (str(diff.seconds) + ' secs')

Solution 3

Using datetime objects: https://docs.python.org/2/library/datetime.html

A good stack overflow post on the topic How to get current time in Python

from datetime import datetime
now = datetime.now()
# wait some time
then = ... some time
# diff is a datetime.timedelta instance
diff = then - now
diff_hours = diff.seconds / 3600
Share:
11,731
Shekhar M Wagaskar
Author by

Shekhar M Wagaskar

Updated on June 28, 2022

Comments

  • Shekhar M Wagaskar
    Shekhar M Wagaskar almost 2 years

    I want to calculate difference between two time in hours using django in sql db the time are stored in timefield.

    I tried this:

    def DesigInfo(request):  # attendance summary
      emplist = models.staff.objects.values('empId', 'name')
      fDate = request.POST.get('fromDate')
      tDate = request.POST.get('toDate')
    
      if request.GET.get('empId_id'):
        sel = attendance.objects.filter(empId_id=request.GET.get('empId_id'),)
        for i in sel:
            # print i.
            # print   i.outTime
            # print i.inTime.hour,i.inTime.minute,i.inTime.second - i.outTime.hour,i.outTime.minute,i.outTime.second
            ss = i.inTime.hour
            ss1 = 12 - ss
            mm = i.outTime.hour
            mm1 = (12 + mm) - 12
            print ss1 + mm1
    
    • Hackaholic
      Hackaholic over 8 years
      you can use any time or datetime module, instead of reinventing the wheel.
  • Shekhar M Wagaskar
    Shekhar M Wagaskar over 8 years
    dude but actually i were stored only time into database using Timefield()
  • Shekhar M Wagaskar
    Shekhar M Wagaskar over 8 years
    suppose time1=10:54:25 and time2=05:22:23 and we calculate ans=timet2-time1 like ss = i.inTime.hour ss1 = 12 - ss mm = i.outTime.hour mm1 = (12 + mm) - 12 print ss1 + mm1 but problem to calculate minut or second
  • Zac
    Zac over 8 years
    As already stated. Do not try to reinvent the wheel: basic types already have methods to obtain time differences. Since I understand that your variables are not datetime objects but time objects I'll adapt the answer.
  • BenJ
    BenJ over 8 years
    That's ok. You can use datetime.datetime.strptime to convert from a string to a time object
  • moni sogani
    moni sogani about 6 years
    giving negative ans if outTime < startTime(i.e outTime = 05:00 and startTime= 13:00)