简体   繁体   English

如何解决无效时间错误

[英]How to fix Invalid Time error

I have the following error: 我有以下错误:

[u"'00:56:93' value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an invalid time."]

Is there a fix for this, for example, no item can be greater than 59? 是否有解决方法,例如,没有项目可以大于59?

So, the function would yield: 因此,该函数将产生:

fix_time('00:56:93')
00:56:59

if you want to carry overflow up: 如果您想进行溢出:

import datetime

stamp = '00:56:93'
h, m, s = map(int, stamp.split(':'))
seconds = h*3600 + m*60 + s
new_stamp = str(datetime.timedelta(seconds=seconds))
# '0:57:33'

if you want to just limit values: 如果您只想限制值:

maxima = (23, 59, 59)
as_numbers = map(int, stamp.split(':'))
with_limits = zip(as_numbers, maxima)
limited = map(min, with_limits)
str(datetime.time(*limited))
# '00:56:59'

and if you are sure you always have exactly two digits, you don't even need to convert to ints: 并且如果您确定始终始终只有两位数,则甚至无需转换为整数:

maxima = ('23', '59', '59')
':'.join(map(min, stamp.split(':'), maxima))
# '00:56:59'

You can use the following function -- 您可以使用以下功能-

def fix_time(value):
    if not value:
        return value
    if not re.match('\d{2}:\d{2}:\d{2}',value):
        return value

    hours, minutes, seconds = int(value.split(':')[0]), int(value.split(':')[1]), int(value.split(':')[2])
    total_seconds = (seconds) + (minutes * 60) + (hours * 60 * 60)
    formatted_seconds = total_seconds % 60
    formatted_minutes = (total_seconds / 60) % 60
    formatted_hours = total_seconds / 3600
    value = '%.2d:%.2d:%.2d' % (formatted_hours, formatted_minutes, formatted_seconds)
    return value

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

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