python 时间处理

来源:互联网 发布:新南威尔士奖学金知乎 编辑:程序博客网 时间:2024/06/13 22:01
def timestamp_to_datetime(timestamp):    """将 13 位整数的毫秒时间戳转化成本地普通时间 (datetime 格式)    :param timestamp: 13 位整数的毫秒时间戳 (1456402864242)    :return: 返回 datetime 格式 {datetime}2016-02-25 20:21:04.242000    """    local_dt_time = datetime.datetime.fromtimestamp(float(timestamp) / 1000.0)    return local_dt_time#时间转换为秒def time_to_second(time2):    time1 = datetime.datetime.strptime(str(time2), "%M:%S.%f")    return time1.microseconddef time_to_mytime(timeme):    '''    '2017-01-19-16-00-44-3700'转换为"16:00:44.370000"    '''    t = datetime.datetime.strptime(timeme, "%Y-%m-%d-%H-%M-%S-%f")    return t.strftime("%H:%M:%S.%f")#两个时间相减,得到秒数差值def time_micro(time_recog,time_handle):    time_re = datetime.datetime.strptime(str(time_recog), "%H:%M:%S.%f")    time_ha = datetime.datetime.strptime(str(time_handle), "%H:%M:%S.%f")    time_result = time_ha - time_re    #return time_result.seconds

return time_result.total_seconds()

def cur_time():    cur_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())    return cur_time

def time_to_mytime(timeme):    '''    '2017-01-19-16-00-44-3700'转换为"16:00:44.370000"    '''    t = datetime.datetime.strptime(timeme, "%Y-%m-%d-%H-%M-%S-%f")    return t.strftime("%H:%M:%S.%f")def time12to24(time_string, formats):    times = time.strftime("%H:%M.%f", time.strptime(time_string, formats))  # 将时间转为hh.mm类型    ftime = datetime.datetime.strptime(times, "%H:%M.%f")  # 将times字符串转为%H.%M的datetime类型    if time_string.find("am") > -1:        if times >= '12.00':            ftime = ftime + datetime.timedelta(hours=36)  # +36小时而不是-12小时的原因:如果未提供年份,则默认为1900,如果-12小时,年份有可能为1899,会异常    elif time_string.find("pm") > -1:        if times < '12.00':            ftime = ftime + datetime.timedelta(hours=12)    times = ftime.strftime("%H:%M.%f")

原创粉丝点击