I have to add these time in one
(2 hr and 50 min)+(1 hr and 20 min) = (4 hr and 10 min)
but how to take these two-time objects as input? I tried using a nested list and dictionary but didn't feel the appropriate way.
I have to add these time in one
(2 hr and 50 min)+(1 hr and 20 min) = (4 hr and 10 min)
but how to take these two-time objects as input? I tried using a nested list and dictionary but didn't feel the appropriate way.
The datetime
module provides a timedelta
class that serves this purpose.
import datetime
time1 = datetime.timedelta(hours=2, minutes=50)
time2 = datetime.timedelta(hours=1, minutes=20)
time3 = time1 + time2
timedelta
objects store fractions of a day in seconds and milliseconds. If you want time3
in hours and minutes, you'll have to compute them from the seconds and milliseconds.
You can try to use datetime, take normal input such as float/int and assign to variables like delta, then you should be able to perform addition.
from datetime import timedelta
delta = timedelta(
seconds=27,
minutes=5,
hours=8
)
delta2 = timedelta(
seconds=33,
minutes=54,
hours=2
)
print (delta+delta2)
output would be: 11:00:00
you can add more fields like days, microseconds, milliseconds, weeks if needed.
One way to add minutes and hours is by using Python's datetime module. First, you specify the time, in this case, hours and minutes. Then, use datetime.timedelta to add the times.
Here is an example:
import datetime
date_and_time = datetime.datetime(2020, 2, 19, 2, 50, 0)
print(date_and_time) # 2020-02-19 02:50:00
time_change = datetime.timedelta(hours=1, minutes=20)
new_time = date_and_time + time_change
print(new_time) # 2020-02-19 04:10:00