如何读取大于60的分钟值并避免ValueError:时间数据“60:01”与格式“%M:%S”不匹配

2024-04-28 13:01:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它读取一个损坏的.CUE文件,该文件没有索引00,并检索每个曲目条目的分秒值。找到这些值后,脚本将每个轨迹减去02秒(从而创建precap并更正.CUE文件),并创建一个新的correct.CUE文件。在遇到包含大于60的分钟值的.CUE文件之前,脚本工作得非常出色。出现以下错误:

ValueError: time data '60:01' does not match format '%M:%S'

我使用datetime是因为我不能简单地将每个音轨条目的02秒减去一个整数。当条目的'INDEX 01'seconds值为01秒时,减去02秒也会影响分钟值,因为这意味着分钟值将减少01。你知道吗

这是执行格式化和减法的代码的一部分。它工作正常,直到遇到一个分钟值大于60:

from datetime import datetime

WrongIndex = '60:01'
NewIndex = '00:02'
format = '%M:%S'
time = datetime.strptime(WrongIndex, format) - datetime.strptime(NewIndex, format)

本例中的预期返回值应为“59:59”。你知道吗

我想知道是否有其他方法使用大于60的分钟值,因为这些文件的最大长度可以达到79.8分钟。你知道吗


Tags: 文件目的脚本formatdatetimetime轨迹错误
3条回答

你需要做一些转换。我会把你的值转换成整数。如果minutes大于59,则将其添加到hours。之后,我们可以创建一个datetime对象,用它进行减法运算。为了得到分钟数,我们以秒为单位,将其除以60

from datetime import datetime

def to_time(value):
    "Takes in values as '%M:%S' and return datetime object"

    # value casting to integers 
    minutes, seconds = [int(i) for i in value.split(':')]

    # if minutes is greater than 59 pass it to hour
    hour = 0
    if minutes > 59:
        hour = minutes//60
        minutes = minutes%60

    return datetime.strptime(f'{hour}:{minutes}:{seconds}', '%H:%M:%S')


# now our calculations 
wrong_index = '60:01'
new_index = '00:02'

time_ = to_time(wrong_index) - to_time(new_index)

print(time_.seconds/60)

我不认为datetime对象真的是适合您的问题的数据结构。这种类型期望引用一个真实的时钟时间,而不仅仅是任意的分秒数。如果您坚持使用datetime,则更合适的类型可能是timedelta,它表示一段时间,与任何特定的时钟或日历无关。但是对于timedeltas没有等价物

如果没有解析,你就不会从datetime中得到什么。所以我建议你自己来解析。这不是很难:

minutes, seconds = map(int, WrongIndex.split(':'))

这只是将输入字符串(例如'60:01')拆分为一个包含两个值的列表(['60', '01'])。然后将字符串值转换为整数。然后将这两个整数赋给变量minutesseconds。你知道吗

为了简化计算,您可以将这两个值合并为一个整数,即秒数:

seconds += minutes * 60

然后可以减去两秒的偏移量,并将秒数转换回时间字符串:

seconds -= 2    # or parse the offset string if you don't want to hard code two seconds

result = "{:02}:{:02}".format(*divmod(seconds, 60))

在格式化步骤中,我使用divmod函数,它在一个步骤中计算一个楼层划分和一个模数(它以元组的形式返回二者)。你知道吗

这个怎么样:

import datetime

WrongIndex = '60:01'
NewIndex = '00:02'

wrong_time =  WrongIndex.split(':')
new_index = NewIndex.split(':')

old_seconds = int(wrong_time[0])*60 + int(wrong_time[1])
new_seconds = int(new_index[0])*60 + int(new_index[1])

time = datetime.timedelta(seconds=old_seconds-new_seconds)
print(time)

相关问题 更多 >