Shekhar M Wagaskar
Shekhar M Wagaskar

Reputation: 19

calculate difference between two time in hour

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

Upvotes: 1

Views: 13107

Answers (4)

ARKhan
ARKhan

Reputation: 1975

The easiest way through I achieve is the comment of Zac given above. I was using relativedelta like this

from dateutil import relativedelta
difference = relativedelta.relativedelta( date1, date2)
no_of_hours = difference.hours

but it did not give me correct result when the days changes. So, I used the approach expressed above:

no_of_hours = (difference.days * 24) + (difference.seconds / 3600)

Please note that you will be getting negative value if date2 is greater than date1. So, you need to swipe the position of date variables in relativedelta.

Upvotes: 0

Wahab
Wahab

Reputation: 11

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')

Upvotes: 1

Zac
Zac

Reputation: 2250

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)

Upvotes: 3

BenJ
BenJ

Reputation: 456

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

Upvotes: 1

Related Questions