python time 时间模块

time():获取当前系统的时间戳
ctime():以人类可读的方式打印当前系统时间
sleep():接受一个参数,表示休眠时间

 1 #!/usr/bin/env python
 2 #coding:utf8
 3 import time 
 4 print time.time()
 5 print time.ctime()
 6 time.sleep(5)
 7 print time.ctime()
 8 
 9 输出结果:
10 1405706231.52
11 Sat Jul 19 01:57:11 2014
12 Sat Jul 19 01:57:16 2014
View Code

localtime():接受一个时间戳,并把它转化为一个当前时间的元组。不给参数的话就会默认将time.time()作为参数传入
mktime():和time.localtime()相反,它把一个时间元组转换成时间戳(这个必须要给一个参数)

time.localtime():
索引 属性 含义
0 tm_year
1 tm_mon
2 tm_mday
3 tm_hour
4 tm_min
5 tm_sec
6 tm_wday 一周中的第几天
7 tm_yday 一年中的第几天
8 tm_isdst 夏令时
 1 #!/usr/bin/env python
 2 #coding:utf8
 3 import time
 4 print time.ctime() 
 5 now=time.localtime()
 6 print now
 7 print now.tm_year
 8 print now.tm_mon
 9 print now.tm_mday
10 print now.tm_hour
11 print now.tm_min
12 print now.tm_sec
13 print now.tm_wday
14 print now.tm_yday
15 print time.mktime(now)
16 
17 输出结果:
18 Sat Jul 19 02:19:14 2014
19 time.struct_time(tm_year=2014, tm_mon=7, tm_mday=19, tm_hour=2, tm_min=19, tm_sec=14, tm_wday=5, tm_yday=200, tm_isdst=0)
20 2014
21 7
22 19
23 2
24 19
25 14
26 5
27 200
28 1405707554.0
View Code

asctime():把一个时间元组表示为:ctime() (“Sun Jul 28 03:35:26 2013”)这种格式,不给参数的话就会默认将time.localtime()作为参数传入
time.gmtime():将一个时间戳转换为UTC+0时区(中国应该是+8时区,相差8个小时)的时间元组,不给参数的话就会默认将time.time()作为参数传入

 1 #!/usr/bin/env python
 2 #coding:utf8
 3 import time
 4 now=time.localtime()
 5 print now
 6 print time.asctime(now)
 7 print time.gmtime()
 8 
 9 输出结果:
10 time.struct_time(tm_year=2014, tm_mon=7, tm_mday=19, tm_hour=2, tm_min=23, tm_sec=44, tm_wday=5, tm_yday=200, tm_isdst=0)
11 Sat Jul 19 02:23:44 2014
12 time.struct_time(tm_year=2014, tm_mon=7, tm_mday=18, tm_hour=18, tm_min=23, tm_sec=44, tm_wday=4, tm_yday=199, tm_isdst=0)
View Code

time.strftime(format,time.localtime()):将一个时间元组转换为格式化的时间字符,不给时间元组参数的话就会默认将time.localtime()作为参数传入

format:

属性 格式 含义 取值范围(格式)
年份 %y 去掉世纪的年份 00-99
%Y 完整的年份  
%j 一年中的第几天 001-366
月份 %m 月份 1月12日
%b 本地简化月份的名称 简写英文月份
%B 本地完整月份的名称 完整英文月份
日期 %d 一个月中的第几天 1月31日
小时 %H 一天中的第几个小时(24小时制) 00-23
%l 第几个小时(12小时制) “01-12”
分钟 %M 分钟数 00-59
%S 00-59
星期 %U 一年中的星期数(从星期天开始算) 00-53
%W 一年中的星期数(从星期一开始算)  
%w 一个星期的第几天 0-6
时区 %Z 中国:应该是GMT+8(中国标准时间) 求大神扫盲
其他 %x 本地相应日期 日/月/年
%X 本地相印时间 时:分:秒
%c 详细日期时间 日/月/年 时:分:秒
%% ‘%’字符 ‘%’字符
%p 本地am或者pm的相应符 AM    or    PM

例如web日志里面的时间格式就是time.strftime('%d/%b/%Y:%X')

1 #!/usr/bin/env python
2 #coding:utf8
3 import time
4 print time.strftime('%d/%b/%Y:%X')
5 
6 输出结果:
7 19/Jul/2014:02:34:47
View Code

time.strptime(stringtime,format):将时间字符串根据指定的格式化符转换成数组形式的时间,

1 #!/usr/bin/env python
2 #coding:utf8
3 import time
4 print time.strptime('19/Jul/2014:02:34:47', '%d/%b/%Y:%X')
5 
6 输出格式:
7 time.struct_time(tm_year=2014, tm_mon=7, tm_mday=19, tm_hour=2, tm_min=34, tm_sec=47, tm_wday=5, tm_yday=200, tm_isdst=-1)
View Code
原文地址:https://www.cnblogs.com/pping/p/3854525.html