在Python中添加持续时间 [英] Adding up time durations in Python

查看:80
本文介绍了在Python中添加持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中添加一系列拆分。时间以 00:08:30.291之类的字符串开头。我似乎找不到正确的方法来使用Python对象或API来使此操作方便/优雅。看来时间对象并没有使用微秒,因此我正在使用datetime的strptime成功解析字符串。但是日期时间似乎并没有增加,我真的更希望不要溢出几天(即23 + 2小时= 25小时)。我可以使用datetime.time,但它们都不添加。 Timedeltas似乎合适,但从其他事物转换为其他事物似乎有点尴尬。也许我在这里缺少明显的东西。我希望能够:

I would like to add up a series of splits in Python. The times begin as strings like "00:08:30.291". I can't seem to find the right way to use the Python objects or API to make this convenient/elegant. It seems that the time object doesn't use microseconds, so I'm using datetime's strptime to parse the strings, successfully. But then datetimes don't seem to add, and I really prefer not to overflow into days (i.e. 23 + 2 hours = 25 hours). I can use datetime.time but they don't add either. Timedeltas would seem appropriate but seem a little awkward to convert from/to other things. Perhaps I am missing something obvious here. I would like to be able to:

for timestring in times:
    t = datetime.strptime("%H:%M:%S.%f", timestring).time
    total_duration = total_duration + t
print total_duration.strftime("%H:%M:%S.%f")


推荐答案

您正在使用的是时差,这就是为什么使用 datetime.timedelta 仅在此处适用:

What you're working with is time differences, that's why using datetime.timedelta is only appropriate here:

>>> import datetime
>>> d1 = datetime.datetime.strptime("00:08:30.291", "%H:%M:%S.%f")
>>> d1
datetime.datetime(1900, 1, 1, 0, 8, 30, 291000)
>>> d2
datetime.datetime(1900, 1, 1, 0, 2, 30, 291000)
>>> dt1 = datetime.timedelta(minutes=d1.minute, seconds=d1.second, microseconds=d1.microsecond)
>>> dt2 = datetime.timedelta(minutes=d2.minute, seconds=d2.second, microseconds=d2.microsecond)
>>> fin = dt1 + dt2
>>> fin
datetime.timedelta(0, 660, 582000)
>>> str(fin)
'0:11:00.582000'

另外,请不要对变量使用 sum 之类的名称,您将隐藏内置变量。

Also, please don't use such names as sum for your variables, you're shadowing built-in.

这篇关于在Python中添加持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆