Python(26):【Python中常用的库系列】——时间模块time(处理不规律时间格式为:2020-03-21 15:02:36)

一、时间模块转换图

在这里插入图片描述

二、时间模块转换举例

1.获取时间戳
python时间戳取整为10位,单位为s

import time

print(time.time())  # 1621235477.11
print(int(time.time()))  # 1621235477

2.休眠

time.sleep(3)

3.获取时间元组

#显示当前时间的时间元组
print(time.localtime())
print(time.localtime(time.time())) # 同time.localtime()

在这里插入图片描述

#显示一个小时前的时间元组
print(time.localtime(time.time()-3600))

在这里插入图片描述

# 显示utc时间的时间元组
print(time.gmtime())

在这里插入图片描述

4.时间元组与其他格式的相互转换

时间元组 → 格式化时间

time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
# 2021-05-17 15:17:32

格式化时间 → 时间元组

time.strptime(s,'%Y-%m-%d %H:%M:%S')

时间元组 → 时间戳

print(time.mktime(t)) # 1621235956.0

时间戳格式 → 时间元组

print(time.localtime(time.time())) # 获取时间戳
# time.struct_time(tm_year=2022, tm_mon=1, tm_mday=14, tm_hour=15, tm_min=1, tm_sec=24, tm_wday=4, tm_yday=14, tm_isdst=0)

例:将时间戳转为格式化时间

print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

# 2022-01-14 15:03:16

三、练习

需求:假如银行卡在2019-07-24 17:04:00被冻结,求出已过时间和解冻剩余时间,并且时间实现一秒一秒的动态跳动

import time

def second1(seconds):  # 把秒数转换为天时分秒的函数,方法1
    day = int(seconds // (24 * 60 * 60))
    shi = int(seconds % (24 * 60 * 60) // (60 * 60))
    fen = int(seconds % (24 * 60 * 60) % (60 * 60) // 60)
    miao = int(seconds % (24 * 60 * 60) % (60 * 60) % 60)
    return (day, shi, fen, miao)


# ------------------------------------------------------------------------------------
def second2(seconds):  # 把秒数转换为时分秒的函数,方法2
    day = int(seconds // (24 * 60 * 60))  # 天=总秒数整除每天的秒数
    shi = int((seconds - day * 24 * 60 * 60) // 3600)  # 时=总的秒数-天数的秒数
    fen = int(((seconds - day * 24 * 60 * 60 - shi * 60 * 60) // 60))  # 分=总的秒数-天数的秒数-时的秒数
    miao = int((seconds - day * 24 * 60 * 60 - shi * 60 * 60 - fen * 60))  # 秒=总的秒数-天数的秒数-时的秒数-分的秒数
    return (day, shi, fen, miao)


# ——-----------------------------------------------------------------------------------
冻结时间 = '2019-07-24 17:04:00'
c = time.mktime(time.strptime(冻结时间, '%Y-%m-%d %H:%M:%S'))  # 把时间戳转化为元组-->再 把时间戳再转化为秒
while True:
    now_time = time.time()  # 获取当前时间
    f = now_time - c  # 获取现在距离冻结的时间的秒数
    已过时间 = second1(f)
    print('已经过去', 已过时间[0], '天', 已过时间[1], '时', 已过时间[2], '分', 已过时间[3], '秒', end='       ')
    j = 7 * 24 * 3600 - f  # 冻结七天一共的秒数-已过的秒数为还剩的秒数
    剩下时间 = second2(j)
    print('还需要', 剩下时间[0], '天', 剩下时间[1], '时', 剩下时间[2], '分', 剩下时间[3], '秒')
    time.sleep(1)

在这里插入图片描述

四、统一处理时间标准为:(2020-03-21 15:02:36)

1.从字符串中匹配 【年-月-日】

import re

def format_date(str):
    date = re.findall('\d{4}-\d{2}-\d{2}', str)
    if date:
        return date
    else:
        return '没有符合的时间格式'


a = '2020-08-06啊撒打算的啊2015-3-1 2005-03-21'
print(format_date(a))

结果:在这里插入图片描述


2.随机生成【时:分:秒】

# -------------------------------------------------------随机生成时分秒
import random


def get_random_time():
    H = str(random.randint(0, 24))
    M = str(random.randint(0, 60))
    S = str(random.randint(0, 60))
    random_time = [H, M, S]
    for i in range(0, len(random_time)):
        if len(random_time[i]) == 1:
            random_time[i] = '0' + random_time[i]
    time_ = ':'.join(random_time)
    return time_
    
print(get_random_time())

结果:在这里插入图片描述


3.处理此类形式:【2019-11-20T10:06:09+08:00】

# 1.匹配时间2019-11-20T10:06:09+08:00
def verify_datetime(datetime_):
    pattern = r'((?!0000)[0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29) (20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$'
    if re.match(pattern, datetime_):
        return True


# 2.处理匹配到的时间
def format_date_tz(raw_date):
    date = raw_date.replace('T', ' ').replace('Z', '').split('+')[0]
    if not verify_datetime(date):
        raise ValueError(raw_date, date)
    return date

print(format_date_tz('2019-11-20T10:06:09+08:00'))

结果:在这里插入图片描述


4.将2020年3月14日处理为【2020-03-14】

x = '2020年3月14日'


# 例如格式为2016年5月17日,月日可能不足两位的
def format_time(date):
    a = date.replace('年', '-').replace('月', '-').strip('日')
    b = a.split('-')
    for i in range(2):
        b[1] = b[1].zfill(2)  # 左填充
        b[2] = b[2].zfill(2)
    b = '-'.join(b)
    return b


print(format_time(x))

结果:在这里插入图片描述


5.获取【几天前/几月前/几周前/几年前】的时间

def get_date_ago(date):
    import datetime
    if date.find('月') != -1:
        month_ago = int(re.findall('(.*?)月', date)[0])
        date = datetime.date.today() - datetime.timedelta(days=int(month_ago * 30))
    elif date.find('天') != -1:
        day_ago = int(re.findall('(.*?)天', date)[0])
        date = datetime.date.today() - datetime.timedelta(days=int(day_ago))
    elif date.find('年') != -1:
        year_ago = int(re.findall('(.*?)年', date)[0])
        date = datetime.date.today() - datetime.timedelta(days=int(year_ago * 365))
    elif date.find('周') != -1:
        week_ago = int(re.findall('(.*?)周', date)[0])
        date = datetime.date.today() - datetime.timedelta(days=int(week_ago * 7))
    return date

print(get_date_ago('3天前'))
print(get_date_ago('3周前'))
print(get_date_ago('3月前'))
print(get_date_ago('3年前'))

结果:在这里插入图片描述


6.处理英文月份和固定格式的格式

符号含义
%y两位数的年份表示(00-99)
%Y四位数的年份表示(0000-9999)
%m月份(01-12)
%d月内中的一天(0-31)
%H24小时制小时数(0-23)
%I12小时制小时数(01-12)
%M分钟数(00-59)
%S秒(00-59)
%a本地简化星期名称
%A本地完整星期名称
%b本地简化的月份名称
%B本地完整的月份名称
%c本地相应的日期表示和时间表示
%j年内的一天(001-366)
%p本地A.M.或P.M.的等价符
%U一年中的星期数(00-53)星期天为星期的开始
%w星期(0-6),星期天为星期的开始
%W一年中的星期数(00-53)星期一为星期的开始
%x本地相应的日期表示
%X本地相应的时间表示
%Z当前时区的名称
%%%号本身
def format_Date1(date):
    import datetime
    time_format = str(datetime.datetime.strptime(date, '%b %d, %Y, %H:%M:%S'))
    return time_format


print(format_Date1('Dec 4, 2019, 4:25:41'))

结果:在这里插入图片描述