1👍
If you want to compute the total hours in a datetime.timedelta
object, which is what you get when you compute the difference between to datetime.datetime
objects, you can use total_seconds
:
td = datetime.datetime.now() - datetime.datetime(2021, 2, 15)
total_hrs = td.total_seconds() // 3600
I don’t get why you can’t do directly self.finish_work - self.start_work
? And also how can that be a negative number? You cannot finish working one day before starting, so I assume, that your code has an issue. Probably in the use of datetime.combine
where a job is started at 16:00 on day X and finished at 1:00 on day X + 1. For your code the start and finishing dates will be the same and only the hour will change, giving you the negative difference.
0👍
It turned out to be solved. Added a condition: if self.finish_work < self.start_work:
add 24 hours
def hours_work(self):
if self.finish_work < self.start_work:
time = datetime.combine(date.today(), self.finish_work) + timedelta(hours=24)
result = time - datetime.combine(date.today(), self.start_work)
else:
result = datetime.combine(date.today(), self.finish_work) - datetime.combine(date.today(), self.start_work)
hours_work1 = str(result).rsplit(':', 1)[0]
hours_worked = hours_work1
return hours_worked
Source:stackexchange.com