-3

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.

Him
  • 5,257
  • 3
  • 26
  • 83
Mr.Shah
  • 61
  • 7
  • 3
    These aren't [time](https://docs.python.org/3/library/datetime.html#datetime.time) objects. – Peter Wood Dec 29 '20 at 17:19
  • 6
    It's not clear what object type those "time objects" are, since that's not valid python at all. If you're using built-in objects like `datetime`, you can just add two `timedelta`s together via the `+` operator. See: https://docs.python.org/3/library/datetime.html#available-types. It's not clear how you want those time objects created, or why or how you're trying to use a nested list or dictionary. Please give some background info and ideally a [mre]. – Random Davis Dec 29 '20 at 17:22

3 Answers3

1

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.

Him
  • 5,257
  • 3
  • 26
  • 83
  • how to take it from user input? – Mr.Shah Dec 29 '20 at 17:50
  • This depends on how users are entering the data. If it's coming in as single string, you may want to do [something like this](https://stackoverflow.com/questions/4628122/how-to-construct-a-timedelta-object-from-a-simple-string). If you have control over how users are inputting the data, then you may want to search for and/or ask a separate question about getting user input in python. – Him Dec 29 '20 at 18:00
0

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.

Md Sajid
  • 131
  • 1
  • 1
  • 13
0

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
Leonardo
  • 272
  • 3
  • 16