简体   繁体   中英

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.

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

Try this

import datetime

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM