python -- 格式化time

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值