内置函数
标准库,namespace名称空间;
datetime,对日期、时间、时间戳的处理:
datetime类:类方法;datetime对象;
类方法:
today(),返回本地时区当前时间的datetime对象;
now(tz=None),返回当前时间的datetime对象,时间到微秒,如果tz为None,返回和today()一样;
utcnow(),没有时区的当前时间;
fromtimestamp(timestamp,tz=None),从一个时间戳返回一个datetime对象;
datetime对象:
timestamp(),返回一个到微秒的时间戳;
构造方法:
In [14]: a=datetime.datetime(2018,3,26,19,12,29,79043) #year,month,day,hour,minute,second,microsecond,取datetime对象的年月日时分秒微秒
In [15]: a
Out[15]: datetime.datetime(2018, 3, 26, 19, 12, 29, 79043)
In [16]: a=datetime.datetime(2018,3,26) #至少要给year,month,day,hour,minute会补0
In [17]: a
Out[17]: datetime.datetime(2018, 3, 26, 0, 0)
weekday(),返回星期的天,周一0,周日6,如a.weekday();
isoweekday(),返回星期的天,周一1,周日7,如a.isoweekday();
date(),返回日期date对象,a,date();
time(),返回时间time对象,a.time();
replace(),修改并返回新的时间;
isocalendar(),返回一个三元组(年、周数、周的天),a.isocalendar();
注:
编程时一般都不设置时区;
时间戳,格林威治时间1970-1-1,0点到现在的秒数,与时区无关;
例:
In [1]: import datetime
In [2]: datetime.datetime.now()
Out[2]: datetime.datetime(2018, 3, 26, 19, 3, 12, 8146)
In [3]: datetime.datetime.today()
Out[3]: datetime.datetime(2018, 3, 26, 19, 3, 23, 298291)
In [4]: datetime.datetime.utcnow()
Out[4]: datetime.datetime(2018, 3, 26, 11, 3, 42, 720141)
In [5]: a=datetime.datetime.now()
In [6]: a.timestamp()
Out[6]: 1522062256.146931
In [7]: type(a)
Out[7]: datetime.datetime
In [8]: a=a.timestamp()
In [9]: type(a)
Out[9]: float
In [10]: b=datetime.datetime.fromtimestamp(a)
In [11]: b
Out[11]: datetime.datetime(2018, 3, 26, 19, 4, 16, 146931)
In [12]: b=datetime.datetime.fromtimestamp(int(a)) #微秒丢了
In [13]: b
Out[13]: datetime.datetime(2018, 3, 26, 19, 4, 16)
In [14]: a=datetime.datetime(2018,3,26,19,12,29,79043)
In [15]: a
Out[15]: datetime.datetime(2018, 3, 26, 19, 12, 29, 79043)
In [16]: a=datetime.datetime(2018,3,26)
In [17]: a
Out[17]: datetime.datetime(2018, 3, 26, 0, 0)
In [18]: a.weekday()
Out[18]: 0
In [19]: a.isoweekday()
Out[19]: 1
In [20]: a.date()
Out[20]: datetime.date(2018, 3, 26)
In [21]: a.time()
Out[21]: datetime.time(0, 0)
In [22]: a.isocalendar()
Out[22]: (2018, 13, 1)
日期格式化:
类方法,datetime.datetime.strptime(date_string,format),返回datetime对象,new datetime parsed from a string;
对象方法,a.strftime(format),返回字符串,string format;
字符串format函数格式化;
例:
In [37]: dt=datetime.datetime.strptime('27/3/18 9:30','%d/%m/%y %H:%M') #类方法,返回datetime对象,%y(小写短的),%Y(大写长的)
In [38]: dt
Out[38]: datetime.datetime(2018, 3, 27, 9, 30)
In [39]: dt.strftime('%Y-%m-%d %H:%M:%S') #对象方法
Out[39]: '2018-03-27 09:30:00'
In [40]: '{0:%Y}/{0:%m}/{0:%d} {0:%H}:{0:%M}:{0:%S}'.format(dt) #要加0,否则位置对不上
Out[40]: '2018/03/27 09:30:00'
In [41]: '{}/{}/{}'.format(dt.year,dt.month,dt.day) #常用
Out[41]: '2018/3/27'
timedelta对象,时间差对象:
构造方法:datetime.timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,weeks=0)
year=datetime.timedelta(days=365)
total_seconds(),返回时间差的总秒数;
例:
In [44]: d=datetime.timedelta(days=1) #构造时间差为1天
In [45]: d
Out[45]: datetime.timedelta(1)
In [46]: h=datetime.timedelta(hours=24) #构造时间差为1天
In [47]: h
Out[47]: datetime.timedelta(1)
In [48]: datetime.datetime.now()-d
Out[48]: datetime.datetime(2018, 3, 26, 10, 4, 0, 842544)
In [49]: d1=datetime.datetime.now()
In [50]: d2=datetime.datetime.now()
In [51]: td=d2-d1
In [52]: td.total_seconds()
Out[52]: 8.391767
In [53]: (datetime.datetime.now()-d1).total_seconds()
Out[53]: 72.024944
标准库,time;
id(),标识,返回对象的唯一标识,cpython返回内存地址;
hash(),哈希,返回一个对象的哈希值,散列值(定义域、值域、哈希空间、散列空间、根据哈希算法,哈希冲突少的算法好);
type(),类型,返回对象的类型;
float(),int(),bin(),hex(),oct(),bool(),list(),tuple(),dict(),set(),complex(),bytes(),bytearray(),类型转换;
input([prompt]),输入,接收用户输入,返回一个字符串;
print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False),打印,打印输出,默认使用空格分割,换行结尾,输出到控制台;
len(),对象长度,返回一个集合类型的元素个数;
isinstance(obj,class_or_tuple),判断对象是否属于某种类型或元组中列出某个类型;
issubclass(cls,class_or_tuple),判断类型cls是否是某种类型的子类或元组中列出的某个类型的子类;
In [4]: issubclass(bool,int)
Out[4]: True
abs(num),绝对值,num为数值;
max(),min(),返回可迭代对象中最大值和最小值,返回多个参数中最大值和最小值;
round(num),四舍六入五取偶,银行家算法;
pow(x,y),等价于x**y;
range(stop),从0开始到stop-1的可迭代对象,不是迭代器;
range(start,stop[,step]),从start开始到stop-1结束步长为step的可迭代对象;
divmod(x,y),等价于tuple(x//y,x%y),divmod(3,5);
sum(iterable[,start]),对可迭代对象的所有数值元素求和,sum(range(1,100,2),累加;
chr(i),给一个一定范围的整数返回对应的字符,Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.;
ord(c),返回字符对应的整数,Return the Unicode code point for a one-character string.;
str(),呈现字符串的表达形式,__str__()魔术方法;
repr(),ascii();
例:
In [1]: isinstance(False,(bool,int,str))
Out[1]: True
In [2]: isinstance(False,int)
Out[2]: True
In [3]: isinstance(True,int)
Out[3]: True
In [5]: round(-0.5)
Out[5]: 0
In [6]: round(-0.6)
Out[6]: -1
In [7]: round(-0.4)
Out[7]: 0
In [8]: divmod(3,5)
Out[8]: (0, 3)
In [9]: sum(range(1,100,2))
Out[9]: 2500
In [10]: sum(range(1,100,2),50) #起始数先加进来
Out[10]: 2550
In [14]: chr(97)
Out[14]: 'a'
In [15]: chr(20013)
Out[15]: '中'
In [16]: ord('a')
Out[16]: 97
In [17]: ord('中')
Out[17]: 20013
In [18]: ord('国')
Out[18]: 22269
In [19]: hex(ord('国'))
Out[19]: '0x56fd'
In [20]: str(5)
Out[20]: '5'
In [21]: repr(5)
Out[21]: '5'
In [22]: ascii(5)
Out[22]: '5'
In [23]: ascii('a')
Out[23]: "'a'"
In [24]: str('a')
Out[24]: 'a'
In [25]: repr('a')
Out[25]: "'a'"
sorted(iterable[,key][,reverse])-->list,排序,返回一个新列表,默认升序,reverse反转;如果lst.sort()在列表上用sort()方法是就地修改,返回值为None,a=lst.sort()相当于a=None这样写没意义;
reversed(seq)-->list_reverseiterator,返回一个翻转元素的迭代器;
enumerate(seq,start=0)-->iterator for index,iterator for value,迭代一个序列,返回索引数字和元素构成的二元组,start索引开始的数字,默认0;
iter(iterable),将一个可迭代对象封装成一个迭代器;
next(iterator),取元素,对一个迭代器取下一个元素,如果元素全部取完,再next()会抛StopIteration异常;
zip(*iterables),拉链函数,像拉链一样,把多个可迭代对象合并在一起,返回一个迭代器,将每次从不同对象中取到的元素合并成元组,一般用于dict,dict(zip('abcde',range(5)))木桶原理;
可迭代对象:
能够通过迭代一次次返回不同元素的对象,所谓相同不是指值是否相同,而是元素在容器中是否是同一个,如list中值可重复;
可以迭代,但是未必有序,未必可索引;
可迭代对象有,list,tuple,string,bytes,bytearray,range,set,dict,iterator等;
可用成员运算符in,not in,in本质上就是在遍历对象;
迭代器:
特殊的对象,一定是可迭代对象,具备可迭代对象的特征;
通过iter(iterable)把一个可迭代对象封装成迭代器;
通过next()迭代迭代器对象;
生成器对象,就是迭代器对象;
迭代器不一定是生成器;
例:
In [30]: lst=[3,1,5]
In [31]: sorted(lst)
Out[31]: [1, 3, 5]
In [32]: sorted(lst,reverse=True)
Out[32]: [5, 3, 1]
In [33]: a=sorted(lst,reverse=True)
In [34]: a
Out[34]: [5, 3, 1]
In [36]: sorted({'b':2,'a':1}) #只对dict的key排序
Out[36]: ['a', 'b']
In [37]: a=reversed([3,5,1])
In [38]: a
Out[38]:
In [39]: next(a)
Out[39]: 1
In [40]: next(a)
Out[40]: 5
In [41]: next(a)
Out[41]: 3
In [42]: [reversed([3,5,1])] #不是列表解析,是list_reverseiterator
Out[42]: [
In [43]: [i for i in reversed([3,5,1])] #列表解析
Out[43]: [1, 5, 3]
In [44]: {reversed((2,4))} #该集合元素几个?1个,仅list_reverseiterator对象本身
Out[44]: {
In [45]: (reversed(['c','b','a'])) #最外层()没用,reversed(seq)本身返回的就是迭代器对象
Out[45]:
In [49]: for i in reversed(sorted({1,5,9})): #反转中间结果
...: print(i)
...:
9
5
1
In [50]: for i in enumerate([2,4,6]):
...: print(i)
...:
(0, 2)
(1, 4)
(2, 6)
In [52]: for k,v in enumerate('mno'): #解构
...: print(k,v)
...:
...:
0 m
1 n
2 o
In [61]: it=iter(range(2))
In [62]: next(it)
Out[62]: 0
In [63]: next(it)
Out[63]: 1
In [64]: next(it)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
----> 1 next(it)
StopIteration:
In [65]: 3 in range(10)
Out[65]: True
In [66]: 3 in (x for x in range(10))
Out[66]: True
In [67]: 3 in {x:y for x,y in zip(range(4),range(4,10))} #匹配key
Out[67]: True
In [71]: {x:y for x,y in zip('abcd',range(4))}
Out[71]: {'a': 0, 'b': 1, 'c': 2, 'd': 3}
In [72]: {x:y for x,y in zip('abcd',range(5,20))} #zip(),木桶原理
Out[72]: {'a': 5, 'b': 6, 'c': 7, 'd': 8}
In [73]: for i in iter(range(3)): #可这样用
...: print(i)
...:
0
1
2
In [74]: g=(i for i in range(4))
In [75]: g
Out[75]:
In [76]: print(type(g))
In [77]: list(zip('abcd',range(4)))
Out[77]: [('a', 0), ('b', 1), ('c', 2), ('d', 3)]
In [78]: list(zip('abcd',range(4),'efgh',range(5,9)))
Out[78]: [('a', 0, 'e', 5), ('b', 1, 'f', 6), ('c', 2, 'g', 7), ('d', 3, 'h', 8)]
In [79]: dict(zip('abcde',range(5)))
Out[79]: {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
In [86]: {str(x):y for x,_,y in zip(range(10),range(10),range(10,20))}
Out[86]:
{'0': 10,
'1': 11,
'2': 12,
'3': 13,
'4': 14,
'5': 15,
'6': 16,
'7': 17,
'8': 18,
'9': 19}
In [87]: d=dict(zip('abcd',range(4)))
In [88]: d
Out[88]: {'a': 0, 'b': 1, 'c': 2, 'd': 3}
In [89]: d1=sorted(d.items(),reverse=True) #对二元组排序
In [90]: d1
Out[90]: [('d', 3), ('c', 2), ('b', 1), ('a', 0)]
注:
内置函数:map、filter、reversed、enumerate;
decorator;
generator;
mro中的mixin;
以上用的出神入化,中级水平;