简体   繁体   English

如何在Python中操纵时间对象?

[英]How to manipulate time objects in Python?

I need to work with datetime but I can't find how to subtract or add minutes or seconds from a datetime.time object 我需要使用datetime但找不到从datetime.time对象减去或增加分钟或秒的方法

I've tried to use datetime.timedelta but it doesn't work. 我尝试使用datetime.timedelta,但是它不起作用。

Here is what I've tried 这是我尝试过的

t1=datetime.time(15,45,20)
t2=t1-datetime.timedelta(seconds=40)

I would like to obtain t2=datetime.time(15,44,40) 我想获得t2=datetime.time(15,44,40)

Timedelta works with datetime objects. Timedelta使用日期时间对象。 You could make your time into a datetime (or just start with one, who cares what the year, etc is), and then extract a time object back out. 您可以将时间设置为日期时间(或从一个开始,谁在乎什么年份等等),然后提取一个时间对象。

>>>t1=datetime.datetime(2016, 3, 1, 15,45,20)
>>>t2=t1-datetime.timedelta(seconds=40)
>>>print t2.time()
15:44:40
>>>type(t2.time())
<type 'datetime.time'>

As one of the comments pointed out, this can give you odd results if you don't think about it. 正如评论中指出的那样,如果您不考虑这会给您带来奇怪的结果。 Take 40 seconds off, and end up with a time that's later (but a day earlier on the date data you are ignoring). 请花40秒钟的时间,最后得到的时间要晚一些(但要忽略的日期数据要早一天)。 But you can work around that with minimal logic to catch things that are going to go over 24:00:00 or under 0:0:0. 但是您可以使用最少的逻辑来解决该问题,以捕获将要在24:00:00或0:0:0以下发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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