5 常用模块
- calendar
- time
- datetime
- timeit
- os
- shutil
- zip
- math
- string
- 上述所有模块使用前先导入,string是特例
- calendar,time,datetime的区别
5.1 calendar
跟日历相关的模块
import calendar
# 使用需要先导入
# calendar:获取一年的日历字符串
# 参数
# w = 每个日期之间的间隔字符数
# l = 每周所占用的行数
# c = 每个月之间的间隔字符数
cal = calendar.calendar(2019)
print(type(cal))
print(cal)
cal = calendar.calendar(2019, l=1, c=1)
print(cal)
# isleap: 判断某一年是否是闰年,is开头一般都是判断
print(calendar.isleap(2000))
# leapdays: 获取制定年份之间闰年的个数
print(calendar.leapdays(1998,2018))
print(calendar.leapdays(2018,1998))
#help(calendar.leapdays)
-------------------------------
5
-1
#help(calendar.leapdays)
output:
Help on function leapdays in module calendar:
leapdays(y1, y2)
Return number of leap years in range [y1, y2).
Assume y1 <= y2.
# month() 获取某个月的日历字符串
# 格式:calendar.month(年,月)
# 回值:月日历的字符串
print(calendar.month(2019, 5))
-------------------------------
May 2019
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 31
#monthrange() 获取一个月的周几开始和总天数
# 格式:calendar.monthrange(年,月)
# 回值:元组(周几开始,总天数)
# 注意:周默认 0 -6 表示周一到周天
t = calendar.monthrange(2019,5)
print(t)
w,t = calendar.monthrange(2019,5)
print(w,t)
print(w)
print(t)
------------------------------------
(2, 31)
2 31
2
31
# monthcalendar() 返回一个月每天的矩阵列表
# 格式:calendar.monthcalendar(年,月)
# 回值:二级列表
# 注意:矩阵中没有天数用0表示
m = calendar.monthcalendar(2019, 5)
print(type(m))
print(m)
print("-" * 20)
for i in m:
print(i)
-------------------------
<class 'list'>
[[0, 0, 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, 0, 0]]
--------------------
[0, 0, 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, 0, 0]
# prcal: print calendar 直接打印日历
print(calendar.prcal(2019))
# prmonth() 直接打印整个月的日历
# 格式:calendar.prmonth(年,月)
# 返回值:无
print(calendar.prmonth(2019, 5))
# weekday() 获取周几
# 格式:calendar.weekday(年,月,日)
# 返回值:周几对应的数字
print(calendar.weekday(2019, 5, 10))
5.2 time
5.2.1 时间戳
- 一个时间表示,根据不同语言,可以是整数,也可以是浮点数
- 是从1970年1月1日0分0秒到现在经历的秒数
- 如果表示的时间是1970年以前或者太遥远的未来,可能出现异常
- 32位操作系统能够支持到2038年
5.2.2 UTC时间
- UTC又称为世界协调时间,以英国的格林尼治天文所在地区的时间作为参考的时间,也叫做世界标准时间。
- 中国时间是 UTC+8 东八区
5.2.3 夏令时(已经废弃,了解即可)
- 夏令时就是在夏天的时候将时间调快一小时,本意是督促大家早睡早起节省蜡烛! 每天变成25个小时,本质没变还是24小时
5.2.4 时间元组
-
一个包含时间内容的普通元组
索引 内容 属性 值 0 年 tm_year 2015 1 月 tm_mon 1~12 2 日 tm_mday 1~31 3 时 tm_hour 0~23 4 分 tm_min 0~59 5 秒 tm_sec 0~61 60表示闰秒 61保留值 6 周几 tm_wday 0~6 7 第几天 tm_yday 1~366 8 夏令时 tm_isdst 0,1,-1(表示夏令时)
# 需要单独导入模块
import time
# 时间模块的属性
# timezone: 当前时区和UTC时间相差的秒数,在没有夏令时的情况下的间隔
# altzone 获取当前时区与UTC时间相差的秒数,在有夏令时的情况下,
# daylight 测当前是否是夏令时时间状态, 0 表示是
print(time.timezone)
print(time.altzone)
print(time.daylight)
-------------------
-28800
-32400
0
# 得到时间戳,即距离初始时间的秒数
print(time.time())
-----------------
1558507215.8944747
# localtime,得到当前时间的时间结构
# 可以通过点号操作符得到相应的属性元素的内容
t = time.localtime()
print(type(t))
print("-" * 20)
print(t)
print("-" * 20)
print(t.tm_hour)
----------------------
<class 'time.struct_time'>
--------------------
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=22, tm_hour=14, tm_min=40, tm_sec=35, tm_wday=2, tm_yday=142, tm_isdst=0)
--------------------
14
# asctime() 返回元组的正常字符串化之后的时间格式
# 格式:time.asctime(时间元组)
# 返回值:字符串 Tue Jun 6 11:11:00 2017
t = time.localtime()
tt = time.asctime(t)
print(type(tt))
print(tt)
-----------------------
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=22, tm_hour=14, tm_min=42, tm_sec=59, tm_wday=2, tm_yday=142, tm_isdst=0)
<class 'str'>
Wed May 22 14:42:59 2019
# ctime: 获取字符串化的当前时间
t = time.ctime()
print(type(t))
print(t)
------------------
<class 'str'>
Wed May 22 15:03:37 2019
# clock: 获取cpu时间, 3.0-3.3版本直接使用, 3.6调用有问题
# sleep: 使程序进入睡眠,n秒后继续
for i in range(10):
print(i)
time.sleep(1)
----------------------
0
1
2
3
4
5
6
7
8
9
import time
def p():
time.sleep(2)
t0 = time.clock()
p()
t1 = time.clock()
print(t1 - t0)
# strftime:将时间元组转化为自定义的字符串格式
'''
格式 含义 备注
%a 本地(locale)简化星期名称
%A 本地完整星期名称
%b 本地简化月份名称
%B 本地完整月份名称
%c 本地相应的日期和时间表示
%d 一个月中的第几天(01 - 31)
%H 一天中的第几个小时(24 小时制,00 - 23)
%I 一天中的第几个小时(12 小时制,01 - 12)
%j 一年中的第几天(001 - 366)
%m 月份(01 - 12)
%M 分钟数(00 - 59)
%p 本地 am 或者 pm 的相应符 注1
%S 秒(01 - 61) 注2
%U 一年中的星期数(00 - 53 星期天是一个星期的开始)第一个星期天之前的所有天数都放在第 0 周 注3
%w 一个星期中的第几天(0 - 6,0 是星期天) 注3
%W 和 %U 基本相同,不同的是 %W 以星期一为一个星期的开始
%x 本地相应日期
%X 本地相应时间
%y 去掉世纪的年份(00 - 99)
%Y 完整的年份
%z 用 +HHMM 或 -HHMM 表示距离格林威治的时区偏移(H 代表十进制的小时数,M 代表十进制的分钟数)
%% %号本身
'''
# 表示成 2019年4月18日 15:26格式
import locale # 需要先导入模块
locale.setlocale(locale.LC_CTYPE, 'chinese')
t = time.localtime()
ft = time.strftime("%Y年%m月%d日 %H:%M", t)
print(ft)
-------------------
2019年05月22日 14:48
5.3 datetime模块
- datetime提供日期和时间的运算和表示
import datetime,time
# datetime常见属性
# datetime.date: 一个理想和的日期,提供year, month, day属性
dt = datetime.date(2019, 5, 22)
print(dt)
print(dt.year)
print(dt.month)
print(dt.day)
-----------------
2019-05-22
2019
5
22
这个格式化用的比较多,最好记一下,其他的基本上我都没用过,就当了解吧
# datetime.timedelta
# 表示一个时间间隔
from datetime import datetime, timedelta
t1 = datetime.now()
print( t1.strftime("%Y-%m-%d %H:%M:%S"))
# td表示以小时的时间长度
td = timedelta(hours=1)
# 当前时间加上时间间隔后,把得到的一个小时后的时间格式化输出
print( (t1+td).strftime("%Y-%m-%d %H:%M:%S"))
--------------------
2019-05-22 14:52:45
2019-05-22 15:52:45
5.3.1 datetime.datetime模块
- 提供比较好用的时间而已
- 类定义 class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
- The year, month and day arguments are required.
- MINYEAR <= year <= MAXYEAR
- 1 <= month <= 12
- 1 <= day <= n
- 0 <= hour < 24
- 0 <= minute < 60
- 0 <= second < 60
- 0 <= microsecond < 10**
- 类方法
- datetime.today(): 返回当前本地datetime.随着 tzinfo None.
- datetime.fromtimestamp(time.time()).
- datetime.now([tz]): 返回当前本地日期和时间, 如果可选参数tz为None或没有详细说明,这个方法会像today().
- datetime.utcnow(): 返回当前的UTC日期和时间, 如果tzinfo None ,那么与now()类似.
- datetime.fromtimestamp(timestamp[, tz]): 根据时间戳返回本地的日期和时间.tz指定时区.
- datetime.utcfromtimestamp(timestamp): 根据时间戳返回 UTC datetime.
- datetime.fromordinal(ordinal): 根据Gregorian ordinal 返回
- datetime. datetime.combine(date, time): 根据date和time返回一个新的datetime.
- datetime.strptime(date_string, format): 根据date_string和format返回一个datetime.
- 实例方法
- datetime.date(): 返回相同年月日的date对象.
- datetime.time(): 返回相同时分秒微秒的time对象.
- datetime.replace(kw): kw in [year, month, day, hour, minute, second, microsecond, tzinfo], 与date类似.
- 类属性
- datetime.min: datetime(MINYEAR, 1, 1).
- datetime.max: datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999).
- 实例属性(read-only)
- datetime.year: 1 至 9999
- datetime.month: 1 至 12
- datetime.day: 1 至 n
- datetime.hour: In range(24). 0 至 23
- datetime.minute: In range(60).
- datetime.second: In range(60).
- datetime.microsecond: In range(1000000).
5.4 timeit
import time
# timeit - 时间测量工具
# 测量程序运行时间间隔实验
def p():
time.sleep(2.5)
t1 = time.time()
p()
print(time.time() - t1)
----------------------
2.5001275539398193
import timeit
# 生成列表两种方法的比较 for循环 & 列表生成式
# 如果单纯比较生成一个列表的时间,可能很难实现
c = '''
sum = []
for i in range(1000):
sum.append(i)
'''
# 利用timeit调用代码,执行100000次,查看运行时间
t1 = timeit.timeit(stmt="[i for i in range(1000)]", number=100000)
# 测量代码c执行100000次运行结果
t2 = timeit.timeit(stmt=c, number=100000)
print(t1)
print(t2)
# 此案例中 列表生成式 更快
-------------------------
4.318821437999759
7.035042254000018
# timeit 可以执行一个函数,来测量一个函数的执行时间
def doit():
num = 3
for i in range(num):
print("Repeat for {}".format(i))
# 执行函数,重复10次
t = timeit.timeit(stmt=doit, number=10)
print(t)
------------------------
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
0.0001706670000203303
s = '''
def doIt(num):
for i in range(num):
print("Repeat for {0}".format(i))
'''
# 执行doIt(num)
# setup负责把环境变量准备好
# 实际相当于给timeit创造了一个小环境
# 在创作的小环境中, 代码执行的顺序大致是
#
'''
def doIt(num):
.....
num = 3
doIt(num)
'''
t = timeit.timeit("doIt(num)", setup=s + "num=3", number=10)
print(t)
------------------------
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
0.0008973889998742379