import find_it
import tm2secs2tm
def find_nearest_time(lookfor, target_data): ''' 先格式化时间字符串为seconds,再去搜索,最后将seconds转换为时间字符串返回 '''
what = time2secs(lookfor);
where = [time2secs[k] for k in target_data];
got = find_closest(what, where);
return secs2time(got);
find_it.py
import time
def find_closest(look_for, target_data): '''查找target_data中最接近look_for的项 '''
def whats_the_difference(first, second):
if first == second:
return(0)
elif first > second:
return(first - second)
else:
return(second - first)
max_diff = 9999999
for each_thing in target_data:
diff = whats_the_difference(each_thing, look_for)
if diff == 0:
found_it = each_thing
break
elif diff < max_diff:
max_diff = diff
found_it = each_thing
return(found_it)
tm2secs2tm.py
import time
def format_time(time_string): ''' 格式化时间字符串 '''
tlen = len(time_string)
if tlen < 3:
original_format = '%S'
elif tlen < 6:
original_format = '%M:%S'
else:
original_format = '%H:%M:%S'
time_string = time.strftime('%H:%M:%S', time.strptime(time_string, original_format))
return(time_string)
def time2secs(time_string): ''' 将时间字符串转换为seconds '''
time_string = format_time(time_string)
(hours, mins, secs) = time_string.split(':')
seconds = int(secs) + (int(mins)*60) + (int(hours)*60*60)
return(seconds)
def secs2time(seconds): ''' 将seconds转换为时间字符串 '''
return(time.strftime('%H:%M:%S', time.gmtime(seconds)))