[英]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'
. 我有一个字符串,像这样: '1:48'
: '1:48'
我想在上面加上一些时间,例如15分钟,然后打印'2:03'
。
What is the problem: 问题是什么:
I am newbie to Python and following official documentation, I cannot do it. 我是Python的新手,根据官方文档,我无法做到。
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. 但是我无法从time
库中找到增加时间的方法。 I found that method in datetime
(timedelta) library, but there is not a method which create time object from string. 我在datetime
(timedelta)库中找到了该方法,但是没有一种可以从字符串创建时间对象的方法。
You can create time
objects from string of type 'hh:mm:ss' by using some string operations like: 您可以使用以下字符串操作从“ hh:mm:ss”类型的字符串创建time
对象:
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: 然后,您可以使用timedelta方法添加/减去时间:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.