时间和日历 时间的使用处理无处不在:
日志管理必然会记录时间
统计程序执行开始、结束时间
测试一个函数执行时长
在Python与时间处理相关模块有:time模块和datetime模块
time 模块,提供了2中时间表达方式:
假定一个零点基准,偏移长度换算为按秒的数值型
由9个整数组成的元组struct_time表示的时间
date_time 模块,常用类有4个:
date:日期类,包括属性年、月、日及相关方法
time:时间类,包括属性时、分、秒等及相关方法
datetime:日期时间,继承与date,包括属性年、月、日、时、分、秒等及相关方法,其中年月日必须参数
timedelta:两个datetime值的差,比如相差几天(days)、几小时(hours)、几分(minutes)等。
除了两个以上时间模块,还有calendar 模块还提供一些实用的功能,例如:
time模块 time模块提供时间相关的类和函数。
常用函数 1. 当前时间规浮点数 1 2 3 4 >>> import time>>> seconds = time.time()>>> seconds1649579649.6309361
2.时间数组 1 2 3 4 >>> seconds = time.time()>>> local_time = time.localtime(seconds)>>> local_timetime.struct_time(tm_year=2022 , tm_mon=4 , tm_mday=10 , tm_hour=16 , tm_min=36 , tm_sec=29 , tm_wday=6 , tm_yday=100 , tm_isdst=0 )
3.时间字符串 time类asctime方法,转换struct_time为时间字符串。
1 2 3 4 5 >>> seconds = time.time()>>> local_time = time.localtime(seconds)>>> str_time = time.asctime(local_time)>>> str_time'Sun Apr 10 16:36:29 2022'
4.格式化时间字符串 time类strftime方法,按照时间格式要求,格式化struct_time为时间字符串
1 2 3 4 >>> local_time = time.localtime(time.time())>>> format_time = time.strftime('%Y-%m-%d %H:%M:%S' , local_time)>>> format_time'2022-04-10 16:36:29
5.字符时间转时间数组 time类strptime方法,解析(parse)输入的时间字符串为struct_time类型的时间。
1 2 3 4 5 >>> local_time = time.localtime(time.time())>>> format_time = time.strftime('%Y-%m-%d %H:%M:%S' , local_time)>>> str_to_struct = time.strptime(format_time, '%Y-%m-%d %H:%M:%S' )>>> str_to_structtime.struct_time(tm_year=2022 , tm_mon=4 , tm_mday=10 , tm_hour=16 , tm_min=36 , tm_sec=29 , tm_wday=6 , tm_yday=100 , tm_isdst=-1 )
注意:在使用时第二个参数的时间格式,要与第一个参数的时间格式一致,如果前后格式不匹配,执行会抛出异常
1 >>> str_to_struct = time.strptime('2022-04-10 16:44:30' , '%Y/%m/%d %H:%M:%S' )
抛出异常
1 2 3 4 5 6 7 Traceback (most recent call last): File "<stdin>" , line 1 , in <module> File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py" , line 562 , in _strptime_time tt = _strptime(data_string, format )[0 ] File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py" , line 349 , in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data '2022-04-10 16:44:30' does not match format '%Y/%m/%d %H:%M:%S'
常用的时间格式
时间格式
说明
%Y
年
%m
月 取值[01,12]
%d
天 取值[01,31]
%H
小时 取值[00,23]
%M
分钟 取值[00,59]
%S
秒 取值[00, 61]
datetime模块 学习datetime中的date、datetime、time、timedelta模块
date 常用函数 1.打印当前日志 1 2 3 4 >>> from datetime import date,datetime,time,timedelta>>> tod = date.today()>>> toddatetime.date(2022 , 4 , 10 )
2.当前日期字符串 1 2 3 4 >>> tod = date.today()>>> str_date = date.strftime(tod, '%Y-%m-%d' )>>> str_date'2022-04-10'
3.字符日期转日期 date类里没有strptime方法,它的子类datetime才有解析字符串日期的方法strptime
1 2 3 >>> str_to_date = datetime.strptime('2022-04-10' , '%Y-%m-%d' )>>> str_to_datedatetime.datetime(2022 , 4 , 10 , 0 , 0 )
这样默认转化后的类为datetime。
datetime 常用函数 1.打印当前时间 1 2 3 >>> right = datetime.now()>>> rightdatetime.datetime(2022 , 4 , 10 , 18 , 38 , 0 , 40648 )
2当前时间转字符串显示 1 2 3 4 >>> right = datetime.now()>>> str_time = datetime.strftime(right, '%Y-%m-%d %H:%M:%S' )>>> str_time'2022-04-10 18:38:00'
3.字符时间时间类型 1 2 3 >>> str_to_time = datetime.strptime('2022-04-10 18:40:00' , '%Y-%m-%d %H:%M:%S' )>>> str_to_timedatetime.datetime(2022 , 4 , 10 , 18 , 40 )
timedelta 求两个datetime类型值的差,返回差几天:days,差几小时:hours等。
相减的两个时间,不能一个为date类型,一个为datetime类型,尽管两个是父子关系。
案例:计算还有几天到生日 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import refrom datetime import datetime, datedef get_days_birthday (birthday: str ) -> int : splits = re.split(r'[-.\s+/]' , birthday) splits = [s for s in splits if s] if len (splits) < 3 : raise ValueError('输入格式不正确,至少包括年月日' ) splits = splits[:3 ] birthday = datetime.strptime('-' .join(splits), '%Y-%m-%d' ) tod = date.today() delta = birthday.date() - tod return delta.days print (get_days_birthday('2022-07-05' ))print (get_days_birthday('2022/07/05' ))print (get_days_birthday('2022 07 05' ))print (get_days_birthday('2022/07/05 10:00:00' ))
运行结果
1 2 3 4 5 6 7 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_01.py 85 85 85 85 Process finished with exit code 0
注意:输入时间字符串必须包括年月日,忽略时间值。如果只输入年月,则会抛出异常。
1 print (get_days_birthday('2022-07' ))
运行结果
1 2 3 4 5 6 7 8 9 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_01.py Traceback (most recent call last): File "/Users/lvjing/PycharmProjects/python_base_project/time_sample_01.py", line 24, in <module> print(get_days_birthday('2022-07')) File "/Users/lvjing/PycharmProjects/python_base_project/time_sample_01.py", line 11, in get_days_birthday raise ValueError('输入格式不正确,至少包括年月日') ValueError: 输入格式不正确,至少包括年月日 Process finished with exit code 1
更多时间的小案例 绘制年的日历图 1 2 3 4 5 6 import calendarfrom datetime import datemydate = date.today() year_calendar_str = calendar.calendar(2022 ) print (f'{mydate.year} 年的日历图:{year_calendar_str} \n' )
运行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_02.py 2022年的日历图: 2022 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 1 2 3 4 5 6 1 2 3 4 5 6 3 4 5 6 7 8 9 7 8 9 10 11 12 13 7 8 9 10 11 12 13 10 11 12 13 14 15 16 14 15 16 17 18 19 20 14 15 16 17 18 19 20 17 18 19 20 21 22 23 21 22 23 24 25 26 27 21 22 23 24 25 26 27 24 25 26 27 28 29 30 28 28 29 30 31 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 1 1 2 3 4 5 4 5 6 7 8 9 10 2 3 4 5 6 7 8 6 7 8 9 10 11 12 11 12 13 14 15 16 17 9 10 11 12 13 14 15 13 14 15 16 17 18 19 18 19 20 21 22 23 24 16 17 18 19 20 21 22 20 21 22 23 24 25 26 25 26 27 28 29 30 23 24 25 26 27 28 29 27 28 29 30 30 31 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 1 2 3 4 5 6 7 1 2 3 4 4 5 6 7 8 9 10 8 9 10 11 12 13 14 5 6 7 8 9 10 11 11 12 13 14 15 16 17 15 16 17 18 19 20 21 12 13 14 15 16 17 18 18 19 20 21 22 23 24 22 23 24 25 26 27 28 19 20 21 22 23 24 25 25 26 27 28 29 30 31 29 30 31 26 27 28 29 30 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 1 2 3 4 5 6 1 2 3 4 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 31 Process finished with exit code 0
月的日历图 1 2 3 4 5 6 import calendarfrom datetime import datemydate = date.today() month_calendar_str = calendar.month(mydate.year, mydate.month) print (f'{mydate.year} 年-{mydate.month} 月的日历图:{month_calendar_str} \n' )
运行结果
1 2 3 4 5 6 7 8 9 10 11 12 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_03.py 2022年-4月的日历图: April 2022 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Process finished with exit code 0
判断是否为闰年 1 2 3 4 5 6 7 import calendarfrom datetime import datemydate = date.today() is_leap = calendar.isleap(mydate.year) print_leap_str = "%s年是闰年" if is_leap else "%s年不是闰年\n" print (print_leap_str % mydate.year)
运行结果
1 2 3 4 5 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_04.py 2022年不是闰年 Process finished with exit code 0
判断月有几天 1 2 3 4 5 6 7 import calendarfrom datetime import datemydate = date.today() weekday, days = calendar.monthrange(mydate.year, mydate.month) print (f'{mydate.year} 年-{mydate.month} 月的第一天是那一周的第{weekday} 天\n' )print (f'{mydate.year} 年-{mydate.month} 月共有{days} 天\n' )
运行结果
1 2 3 4 5 6 7 8 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_05.py 2022年-4月的第一天是那一周的第4天 2022年-4月共有30天 Process finished with exit code 0
月的第一天 1 2 3 4 5 from datetime import datemydate = date.today() month_first_day = date(mydate.year, mydate.month, 1 ) print (f"当月第一天:{month_first_day} \n" )
运行结果
1 2 3 4 5 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_06.py 当月第一天:2022-04-01 Process finished with exit code 0
月的最后一天 1 2 3 4 5 6 7 import calendarfrom datetime import datemydate = date.today() _, days = calendar.monthrange(mydate.year, mydate.month) month_last_day = date(mydate.year, mydate.month, days) print (f"当月最后一天:{month_last_day} \n" )
运行结果
1 2 3 4 5 /Users/lvjing/PycharmProjects/python_base_project/venv/bin/python /Users/lvjing/PycharmProjects/python_base_project/time_sample_07.py 当月最后一天:2022-04-30 Process finished with exit code 0