py_ Module II
time module
And time has a relationship we will use the time module. Before using the module, you should first import this module.
# Common method 1.time.sleep (secs) (thread) to postpone a specified time to run. Seconds. 2.time.time () to get the current timestamp
Three ways represents the time of
In Python, there are typically three ways to represent time: time stamp tuples (struct_time), the formatted time string:
(1) timestamp (timestamp): Generally speaking, the timestamp indicates that from January 1970 00:00:00 1st offset press in seconds. We run "type (time.time ())", returns a float.
(2) the formatted time string (Format String): '1999-12-06'
% y represents a two-digit year (00-99 ) % the Y represents a four-digit year (000-9999 ) % m (01-12 ) within% d month of day (0-31 of ) % H 24 hours number (manufactured by 0-23 hours ) % h 12 is the number of the I (manufactured by 01-12 hours ) % M number of minutes (00 = 59 ) % S seconds (00-59 ) % A simplified week local name % A full week of local name % b local simplified month name % B full month name local % C indicates the corresponding local date and time indicates one day (001-366% j years ) % P AM or PM local character equivalent % of U week of the year number (00-53 ) on Sunday as the start of the week % w week (0-6 ), Sunday to begin the week of % W week number of the year (00-53 ) Monday to start the week of % the X-local corresponding date It represents % X-indicates the corresponding local time % Name Z current time zone number %%% itself
(3) tuple (struct_time): struct_time tuple total of nine elements were nine elements :( year, month, day, hour, minute, second, the first few weeks of the year, day of the year, etc.)
Index (Index) | Property (Attribute) | Value (Values) |
---|---|---|
0 | tm_year (years) | For example, 2011 |
1 | tm_mon (月) | 1 - 12 |
2 | tm_mday (Japan) | 1 - 31 |
3 | tm_hour (time) | 0 - 23 |
4 | tm_min (points) | 0 - 59 |
5 | tm_sec (s) | 0 - 60 |
6 | tm_wday(weekday) | 0--6 (0 for Monday) |
7 | tm_yday (the first day of the year) | 1 - 366 |
8 | tm_isdst (whether it is daylight saving time) | The default is 0 |
First, we import the time module, to understand what python represents time in several formats:
# Import time module >>> Import Time # timestamp >>> the time.time () 1,500,875,844.800804 # Time String >>> The time.strftime ( "%% Y-X-M-% D%") '2017-07- 13:54:37 24 ' >>> The time.strftime ( "% D%% Y-H-M-%%% M-S") ' 2017-07-24 13-55-04 ' # time tuples: localtime will convert a timestamp of the current time zone struct_time time.localtime () a time.struct_time (tm_year = 2017, = tm_mon. 7, 24 = tm_mday, tm_hour = 13 is, tm_min = 59, = 37 [tm_sec, tm_wday = 0, = tm_yday 205, tm_isdst = 0)
Summary: The computer is able to identify the timestamp of the time; time string is one can read time; tuple is used to operate the time
Conversion between several formats
# Timestamp -> Structured time # time.gmtime (timestamp) #UTC time, consistent with the local time in London # time.localtime (time stamp) # local time. For example, we now perform in Beijing this method: 8 hours difference with UTC, UTC time is GMT +8 hours = >>> time.gmtime (1.5 billion) a time.struct_time (tm_year = 2017, tm_mon = 7, tm_mday = 14, tm_hour 2 =, = tm_min 40, tm_sec = 0, = tm_wday. 4, tm_yday = 195, the tm_isdst = 0) >>> time.localtime (1.5 billion) a time.struct_time (tm_year = 2017, = tm_mon. 7, tm_mday = 14, = tm_hour 10, tm_min = 40, tm_sec = 0, = tm_wday. 4, tm_yday = 195, the tm_isdst = 0) # structured time -> timestamp # time.mktime (structured time) >>> time_tuple = time.localtime (1.5 billion ) >>> time.mktime (time_tuple) 1500000000.0
Structured Time # -> Time String # The time.strftime ( "Format Definition", "structured Time") if the structured transmission time parameter, the current time is displayed >>> time.strftime ( "% Y-% % D% X-M- ") '2017-07-24 14:55:36' >>> The time.strftime ("% Y-M-% D% ", time.localtime (1.5 billion)) '2017-07- 14 ' # string time -> structured time # the time.strptime (time string, the corresponding string format) >>> the time.strptime ( "2017-03-16", "% D% Y-M-% ") a time.struct_time (tm_year = 2017, = tm_mon. 3, tm_mday = 16, tm_hour = 0, 0 = tm_min, tm_sec = 0, = tm_wday. 3, tm_yday = 75, the tm_isdst = -1) >>> the time.strptime ( "07/24/2017", "% m /% D /% the Y") a time.struct_time (tm_year = 2017, = tm_mon. 7, 24 = tm_mday, tm_hour = 0, 0 = tm_min, tm_sec = 0, 0 = tm_wday , tm_yday = 205, tm_isdst = -1 )
#结构化时间 --> %a %b %d %H:%M:%S %Y串 #time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串 >>>time.asctime(time.localtime(1500000000)) 'Fri Jul 14 10:40:00 2017' >>>time.asctime() 'Mon Jul 24 15:18:33 2017' #时间戳 --> %a %b %d %H:%M:%S %Y串 #time.ctime(时间戳) 如果不传参数,直接返回当前时间的格式化串 >>>time.ctime() 'Mon Jul 24 15:19:07 2017' >>>time.ctime(1500000000) 'Fri Jul 14 10:40:00 2017'
collections模块
方法一:from collections import Counter
Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。Counter类和其他语言的bags或multisets很相似。
c = Counter('abcdeabcdabcaba') print c 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
方法二:from collections import namedtuple
命名元组
我们知道tuple
可以表示不变集合,例如,一个点的二维坐标就可以表示成:
>>> p = (1, 2)
但是,看到(1, 2),很难看出这个tuple是用来表示一个坐标的。
这时,namedtuple
就派上了用场:
a = nametuple('alex',['x','y']) p = alex(1,2) p.x p.y 1 2
类似的,如果要用坐标和半径表示一个圆,也可以用namedtuple
定义:
#namedtuple('名称', [属性list]): Circle = namedtuple('Circle', ['x', 'y', 'r'])
方法三:from collections import defaultdict
默认字典
la = [('红色',1),('黄色',1),('绿色',1),('蓝色',1),('红色',5),('绿色',1),('绿色',1),('绿色',1)] 计算各颜色的数量,格式----{'红色': 6, '黄色': 1, '绿色': 4, '蓝色': 1}
li = [
{'name':'alex','hobby':'抽烟'},
{'name':'alex','hobby':'喝酒'},
{'name':'alex','hobby':'烫头'},
{'name':'alex','hobby':'撩妹'},
{'name':'wusir','hobby':'小宝剑'},
{'name':'wusir','hobby':'游泳'},
{'name':'wusir','hobby':'打牌'},
{'name':'太白','hobby':'烫头'},
{'name':'太白','hobby':'洗脚'},
{'name':'太白','hobby':'开车'},
]
打印出如下格式:{'alex': ['抽烟', '喝酒', '烫头', '撩妹'], 'wusir': ['小宝剑', '游泳', '打牌'], '太白': ['烫头', '洗脚', '开车']}
j = defaultdict(list) # {'dict':[]} for i in li: if j.get(i['name']): j[i['name']].append(i['hobby']) else: j[i['name']] = [i['hobby']] print(dict(j))
方法四:from collections import deque
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
>>> from collections import deque >>> q = deque(['a', 'b', 'c']) >>> q.append('x') >>> q.appendleft('y') >>> q deque(['y', 'a', 'b', 'c', 'x'])
deque除了实现list的append()
和pop()
外,还支持appendleft()
和popleft()
,这样就可以非常高效地往头部添加或删除元素。
datetime,timedelta
from datetime import datetime,timedelta print(datetime.now()) # 时间对象 f = datetime.timestamp(datetime.now()) # 将时间对象转换成时间戳 print(f) print(datetime.fromtimestamp(f)) # 将时间戳转换成时间对象 print(datetime.strptime('2018-11-30','%Y-%m-%d')) # 将字符串转成时间对象 f = datetime.now() print(datetime.strftime(f,'%Y-%m-%d')) # 将时间对象转成字符串 print(datetime.now() - timedelta(weeks=1)) # 重点记*************** # 参数: seconds(秒) microseconds(微秒) milliseconds(毫秒) minutes(分钟) hours(小时) weeks(周)
time模块
和时间有关系的我们就要用到时间模块。在使用模块之前,应该首先导入这个模块。
#常用方法 1.time.sleep(secs) (线程)推迟指定的时间运行。单位为秒。 2.time.time() 获取当前时间戳
表示时间的三种方式
在Python中,通常有这三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串:
(1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
(2)格式化的时间字符串(Format String): ‘1999-12-06’
%y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制小时数(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 当前时区的名称 %% %号本身
(3)元组(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)
索引(Index) | 属性(Attribute) | 值(Values) |
---|---|---|
0 | tm_year(年) | 比如2011 |
1 | tm_mon(月) | 1 - 12 |
2 | tm_mday(日) | 1 - 31 |
3 | tm_hour(时) | 0 - 23 |
4 | tm_min(分) | 0 - 59 |
5 | tm_sec(秒) | 0 - 60 |
6 | tm_wday(weekday) | 0 - 6(0表示周一) |
7 | tm_yday(一年中的第几天) | 1 - 366 |
8 | tm_isdst(是否是夏令时) | 默认为0 |
首先,我们先导入time模块,来认识一下python中表示时间的几种格式:
#导入时间模块 >>>import time #时间戳 >>>time.time() 1500875844.800804 #时间字符串 >>>time.strftime("%Y-%m-%d %X") '2017-07-24 13:54:37' >>>time.strftime("%Y-%m-%d %H-%M-%S") '2017-07-24 13-55-04' #时间元组:localtime将一个时间戳转换为当前时区的struct_time time.localtime() time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=13, tm_min=59, tm_sec=37, tm_wday=0, tm_yday=205, tm_isdst=0)
小结:时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的
几种格式之间的转换
#时间戳-->结构化时间 #time.gmtime(时间戳) #UTC时间,与英国伦敦当地时间一致 #time.localtime(时间戳) #当地时间。例如我们现在在北京执行这个方法:与UTC时间相差8小时,UTC时间+8小时 = 北京时间 >>>time.gmtime(1500000000) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0) >>>time.localtime(1500000000) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0) #结构化时间-->时间戳 #time.mktime(结构化时间) >>>time_tuple = time.localtime(1500000000) >>>time.mktime(time_tuple) 1500000000.0
#结构化时间-->字符串时间 #time.strftime("格式定义","结构化时间") 结构化时间参数若不传,则显示当前时间 >>>time.strftime("%Y-%m-%d %X") '2017-07-24 14:55:36' >>>time.strftime("%Y-%m-%d",time.localtime(1500000000)) '2017-07-14' #字符串时间-->结构化时间 #time.strptime(时间字符串,字符串对应格式) >>>time.strptime("2017-03-16","%Y-%m-%d") time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1) >>>time.strptime("07/24/2017","%m/%d/%Y") time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)
#结构化时间 --> %a %b %d %H:%M:%S %Y串 #time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串 >>>time.asctime(time.localtime(1500000000)) 'Fri Jul 14 10:40:00 2017' >>>time.asctime() 'Mon Jul 24 15:18:33 2017' #时间戳 --> %a %b %d %H:%M:%S %Y串 #time.ctime(时间戳) 如果不传参数,直接返回当前时间的格式化串 >>>time.ctime() 'Mon Jul 24 15:19:07 2017' >>>time.ctime(1500000000) 'Fri Jul 14 10:40:00 2017'
collections模块
方法一:from collections import Counter
Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。Counter类和其他语言的bags或multisets很相似。
c = Counter('abcdeabcdabcaba') print c 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
方法二:from collections import namedtuple
命名元组
我们知道tuple
可以表示不变集合,例如,一个点的二维坐标就可以表示成:
>>> p = (1, 2)
但是,看到(1, 2),很难看出这个tuple是用来表示一个坐标的。
这时,namedtuple
就派上了用场:
a = nametuple('alex',['x','y']) p = alex(1,2) p.x p.y 1 2
类似的,如果要用坐标和半径表示一个圆,也可以用namedtuple
定义:
#namedtuple('名称', [属性list]): Circle = namedtuple('Circle', ['x', 'y', 'r'])
方法三:from collections import defaultdict
默认字典
la = [('红色',1),('黄色',1),('绿色',1),('蓝色',1),('红色',5),('绿色',1),('绿色',1),('绿色',1)] 计算各颜色的数量,格式----{'红色': 6, '黄色': 1, '绿色': 4, '蓝色': 1}
li = [
{'name':'alex','hobby':'抽烟'},
{'name':'alex','hobby':'喝酒'},
{'name':'alex','hobby':'烫头'},
{'name':'alex','hobby':'撩妹'},
{'name':'wusir','hobby':'小宝剑'},
{'name':'wusir','hobby':'游泳'},
{'name':'wusir','hobby':'打牌'},
{'name':'太白','hobby':'烫头'},
{'name':'太白','hobby':'洗脚'},
{'name':'太白','hobby':'开车'},
]
打印出如下格式:{'alex': ['抽烟', '喝酒', '烫头', '撩妹'], 'wusir': ['小宝剑', '游泳', '打牌'], '太白': ['烫头', '洗脚', '开车']}
j = defaultdict(list) # {'dict':[]} for i in li: if j.get(i['name']): j[i['name']].append(i['hobby']) else: j[i['name']] = [i['hobby']] print(dict(j))
方法四:from collections import deque
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
>>> from collections import deque >>> q = deque(['a', 'b', 'c']) >>> q.append('x') >>> q.appendleft('y') >>> q deque(['y', 'a', 'b', 'c', 'x'])
deque除了实现list的append()
和pop()
外,还支持appendleft()
和popleft()
,这样就可以非常高效地往头部添加或删除元素。
datetime,timedelta
datetime datetime Import from, timedelta Print (DateTime.Now ()) # Time Object f = datetime.timestamp (datetime.now ()) # the time of the object into a timestamp Print (F) Print (datetime.fromtimestamp (F)) # converted into time stamp target print (datetime.strptime ( '2018-11-30', '% Y-% m-% d')) # string converted to time the object F = DateTime.Now () Print (datetime.strftime (f, '% Y- % m-% d')) # object into a string of time will be transferred print (datetime.now () - timedelta ( weeks = 1)) # key referred ***** ********** # parameters: seconds (sec) microseconds (sec) milliseconds (ms) minutes (min) hours (h) weeks (weeks)