so I have multiple time value which I wanna subtract with each other but some of the cases I receive negative timedelta how do I convert it into positive without change the actual value
I tried to use abs() but it change the actual value
#for example:
time1=timedelta(hours=23,minutes=25,seconds=00)
time2=timedelta(hours=6,minutes=13,seconds=00)
delta_time_value = time2 -time1
print(delta_time_value) #-1 day, 13:01:00 (ANSWER)
The result which I was getting is -1 day, 13:01:00 but I want the result like this 1 day, 13:01:00 without -ve sign
from datetime import timedelta
time1=timedelta(hours=23,minutes=25,seconds=00)
time2=timedelta(hours=6,minutes=13,seconds=00)
delta_time_value = str(time2 - time1)
print(delta_time_value)
if delta_time_value[0] == "-":
print(delta_time_value[1:])
This is a easy fix, not sure if it is what you are looking for.
time1=timedelta(hours=23,minutes=25,seconds=00)
time2=timedelta(hours=6,minutes=13,seconds=00)
print('{}'.format(time2 -time1).replace("-",""))
Simple usage of str.replace() should suffice as we are not aware which timedelta would be greater. This would replace the "-" (minus) sign only. Thanks.
If you just want the positive value, you can use "abs()" but you need to change the value in a float first:
time1=timedelta(hours=23,minutes=25,seconds=00)
time2=timedelta(hours=6,minutes=13,seconds=00)
delta_time_value = time2 -time1
print(delta_time_value) # OUTPUT -1 day, 13:01:00
print(delta_time_value.total_seconds()) # OUTPUT -61920.0
print(abs(delta_time_value.total_seconds())) # OUTPUT 61920.0
And if you want a string at the end, you just need to do a simple f-string with the value (in 'int' this time):
a = int(abs(delta_time_value.total_seconds()))
format = f'{a // 3600}:{(a % 3600) // 60}:{a % 60}0'
print(format) # OUTPUT 17:12:00
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.