我有以下错误:
[u"'00:56:93' value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an invalid time."]
是否有针对此的修复,例如,没有项目可以大于59?
因此,该函数将产生:
fix_time('00:56:93')
00:56:59
答案 0 :(得分:1)
如果你想进行溢出:
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'
如果您只想限制值:
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'
如果你确定你总是有两位数字,你甚至不需要转换为整数:
maxima = ('23', '59', '59')
':'.join(map(min, stamp.split(':'), maxima))
# '00:56:59'
答案 1 :(得分:0)
您可以使用以下功能 -
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