【问题标题】:Adding up time durations in Python在 Python 中添加持续时间
【发布时间】:2011-01-25 12:15:23
【问题描述】:

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

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")

【问题讨论】:

  • 我不希望时间溢出。这是什么意思? 23 小时 + 2 小时应该等于多少?
  • @SilentGhost:我假设只有很多小时,在这种情况下是 25 小时。
  • 是的,最好是 25。如果您愿意,请考虑这不是必需的。
  • @Sam Brightman 你的意思是duration.days*24*60*60 + duration.seconds?如果你是这个意思,请在问题中写下。
  • S.lott:我不明白你想让我澄清什么

标签: python datetime time


【解决方案1】:

你正在处理的是时差,这就是为什么使用datetime.timedelta 只适合在这里:

>>> 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 这样的名称,您会隐藏内置。

【讨论】:

  • 当然可以,但不优雅地拆开结构并重新创建,特别是对于原型设计。使用当前 API 是否有更简洁/更快捷的方式?感觉timedelta应该有strptime什么的。
  • 我重命名了问题中的变量。
  • 同样它被排除在strftime之外,并且在偶数日期时间和日期/时间之间转换似乎并不简单:d1.time仍然是一个日期时间。
【解决方案2】:
import numpy as np

# read file with one duration per line
with open('clean_times.txt', 'r') as f:
    x = f.read()

# Convert string to list of '00:02:12.31'
# I had to drop last item (empty string)
tmp = x.split('\n')[:-1]

# get list of ['00', 02, '12.31']
tmp = [i.split(':') for i in tmp.copy()]

# create numpy array with floats
np_tmp = np.array(tmp, dtype=np.float)

# sum via columns and divide
# hours/24 minutes/60 milliseconds/1000
# X will be a float array [days, hours, seconds]
# Something like `array([ 0.        , 15.68333333,  7.4189    ])`
X = np_tmp.sum(axis=0) / np.array([24, 60, 1000])

我在这里很开心,但是如果您需要像 '15:41:07.518' 这样的花哨字符串 作为输出,继续阅读

# X will be a float array [hours, hours, seconds]
X = np_tmp.sum(axis=0) / np.array([1, 60, 1000])

# ugly part
# Hours are integer parts
H = int(X[0]) + int(X[1])
# Minutes are  hour fractional part and integer minutes part
tmp_M = (X[0] % 1 + X[1] % 1) * 60
M = int(tmp_M)
# Seconds are minutes fractional part and integer seconds part
tmp_S = tmp_M % 1 * 60 + X[2]
S = int(tmp_S)
# Milliseconds are seconds fractional part
MS = int(tmp_S % 1 * 1000)

# merge string for output
# Something like '15:41:07.518'
result = f'{H:02}:{M:02}:{S:02}.{MS:03}'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-28
    • 2021-06-21
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2015-08-31
    相关资源
    最近更新 更多