MorganFreeFarm
MorganFreeFarm

Reputation: 3723

Python create time object and add some time (minutes) to it

What I want:

I have string, like that: '1:48' I want to add some minutes to it, for example 15 minutes and to print '2:03'.

What is the problem:

I am newbie to Python and following official documentation, I cannot do it.

What I tried:

After google research I found a way to create time object from string, like this:

import time
hours = input()
minutes = input()
time_str = hours + ':' + minutes;

test = time.strptime(time_str, '%H:%M')

print(test)

But I cannot find a method from time library which add time. I found that method in datetime (timedelta) library, but there is not a method which create time object from string.

Upvotes: 4

Views: 7950

Answers (2)

user11168520
user11168520

Reputation:

You can create time objects from string of type 'hh:mm:ss' by using some string operations like:

str=input('Enter time string: ')
h,m,s=str.split(':')

The pass it to time object:

import datetime
t=datetime.time(hour=h,minute=m,second=s)

Then you can use timedelta method to add/subtract time:

td=datetime.timedelta(hour=hd,minute=MD,second=sd)
tf=t+td

Upvotes: 4

Dejan S
Dejan S

Reputation: 1841

Try this

import datetime

t = "22:00"
d = datetime.datetime.strptime(t, '%H:%M')
(d + datetime.timedelta(minutes=15)).strftime("%H:%M")

Upvotes: 3

Related Questions