This question has been flagged
3 Replies
11707 Views

i have 3 fields

check_in_date = fields.Char(string="DateTime Opened", required=False, )
mttr_time = fields.Float(string="MTTR", required=False, )
check_out_date = fields.Datetime(string="DateTime Closed", required=False, )


am trying to get the time difference between 2 datetimes having different formats and here is my function

@api.onchange('check_in_date', 'check_out_date', 'mttr_time')
def calculate_timer(self):
if self.check_in_date and self.check_out_date:
t1 = datetime.strptime(self.check_in_date, '%m/%d/%Y %H:%M:%S')
print('=================================T1')
print('=================================')
print(t1)
print('=================================')
print('=================================')
t2 = datetime.strptime(self.check_out_date, '%Y-%m-%d %H:%M:%S')
print('=================================T2')
print('=================================')
print(t2)
print('=================================')
print('=================================')
t3 = t2 - t1
print('=================================T3')
print('=================================')
print(t3)
print('=================================')
print('=================================')

self.mttr_time = float(t3.days) * 24 + (float(t3.seconds) / 3600)


however if i set the two datetimes to be same/equal i get a difference of negative three(-3.00) hours as shown on this link https://imgur.com/TjnKWY4 am trying to figure out the issue but its like i cant find any assistance will be appreciated


Avatar
Discard
Best Answer

Hi, 
try : 

num_days = abs(fields.Datetime.from_string(t1) - fields.Datetime.from_string(t2)).days
num_seconds = abs(fields.Datetime.from_string(t1) - fields.Datetime.from_string(t2)).seconds
num_hours = parking_end_days * 24 + parking_end_seconds // 3600
num_minutes = parking_end_days * 24 + parking_end_seconds // 60

Thanks
Avatar
Discard
Best Answer

While interpreting your lines I got the correct result.

import datetime as datetime
t1 = datetime.datetime.strptime('11/16/2019 08:00:00', '%m/%d/%Y %H:%M:%S')
t2 = datetime.datetime.strptime('2019-11-16 09:00:00', '%Y-%m-%d %H:%M:%S')
t3 = t2-t1
x = float(t3.days) * 24 + (float(t3.seconds) / 3600)
print "t1:",t1, "t2:", t2, "t3:", t3, "result:", x
t1: 2019-11-16 08:00:00 t2: 2019-11-16 09:00:00 t3: 1:00:00 result: 1.0

Your problem arises when you find the difference from the small-time object with greater. so just add this condition.

if t2 > t1:
t3 = t2-t1
else:
t3 = t1 - t2



Avatar
Discard
Author

I added the condition but it didn't work it was now giving me a difference of positive 3 however i got a solution by adding 3 hours to t2 using

t2 = t2 + timedelta(hours=3)