python添加time_在Python中添加N秒到datetime.time的标准方法是什么?

Given a datetime.time value in Python, is there a standard way to add an integer number of seconds to it, so that 11:34:59 + 3 = 11:35:02, for example?

These obvious ideas don't work:

>>> datetime.time(11, 34, 59) + 3

TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'

>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)

TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'

>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)

TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'

In the end I have written functions like this:

def add_secs_to_time(timeval, secs_to_add):

secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second

secs += secs_to_add

return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)

I can't help thinking that I'm missing an easier way to do this though.

Related

解决方案

You can use full datetime variables with timedelta, and by providing a dummy date then using time to just get the time value.

For example:

import datetime

a = datetime.datetime(100,1,1,11,34,59)

b = a + datetime.timedelta(0,3) # days, seconds, then other fields.

print a.time()

print b.time()

results in the two values, three seconds apart:

11:34:59

11:35:02

You could also opt for the more readable

b = a + datetime.timedelta(seconds=3)

if you're so inclined.

If you're after a function that can do this, you can look into using addSecs below:

import datetime

def addSecs(tm, secs):

fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)

fulldate = fulldate + datetime.timedelta(seconds=secs)

return fulldate.time()

a = datetime.datetime.now().time()

b = addSecs(a, 300)

print a

print b

This outputs:

09:11:55.775695

09:16:55

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值