1、datetime
1.1, get the current date and time
Code:
from datetime import datetime
now = datetime.now()
print (now)
print (type(now)) # 类型是datetime
print (now.year) # 获得datetime的年 同理 月month,日day,时hour,分minute,秒second
print (now.weekday()) # 返回周几,注意是调用weekday()函数
Result: ( week returns an integer, 0 means Monday, 6 means Sunday )
2020-09-02 22:03:41.561002
<type 'datetime.datetime'>
2017
0
1.2 Get the specified date and time
Code:
from datetime import datetime
mytime = datetime(2010, 11, 30, 3, 4, 5)
print (mytime)
Result: ( If you pass in a parameter that does not match the real time, such as 13 months, an error will be thrown )
2010-11-30 03:04:05
1.3 Conversion between string and datetime
Code:
from datetime import datetime
# 字符串转换成datetime
mytime = datetime.strptime('2015-12-11 18:22:33', '%Y-%m-%d %H:%M:%S') # 第二个参数是时间格式
print (mytime)
# datetime转换成字符串
now = datetime.now()
print (now.strftime('%a, %b %d %H:%M'))
result:
2015-12-11 18:22:33
Mon, Jan 23 11:56
1.4 datetime date addition and subtraction
Date addition and subtraction need to import the timedelta
class
Code:
from datetime import datetime, timedelta
mytime = datetime.strptime('2015-12-11 18:22:33', '%Y-%m-%d %H:%M:%S') # 第二个参数是时间格式
print ('当前时间是:%s' % mytime)
print ('往后一天是:%s' % (mytime + timedelta(days=1)))
print ('往前一小时是:%s' % (mytime - timedelta(hours=1))) # 或者还用加法,hours=-1,一个道理
result:
当前时间是:2015-12-11 18:22:33
往后一天是:2015-12-12 18:22:33
往前一小时是:2015-12-11 17:22:33
2. Collections module
2.1 Custom tuple object
Code:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print (p.x, p.y) # 使用属性来调用,注意不是下标
2.2 Use two-way list deque to insert and delete elements
List list
query elements, you can directly use subscripts, but when there are too many list elements, inserting and deleting elements becomes very laborious, because the list is stored linearly, at this time, you can use a two-way list deque
for more efficient execution.
Code:
from collections import deque
L = ['A', 'B', 'C']
dq = deque(L) # dq即为一个双向列表
dq.append('D') # 在末尾添加-----还有pop和popleft,用法同list
dq.appendleft('XXX') # 在开始处添加
print (L) # 原始L的列表不变
print (dq)
print (dq[0]) # 可下标访问
result:
['q', 'A', 'B', 'C']
deque(['XXX', 'A', 'B', 'C', 'D'])
XXX
2.3 Use defaultdic
In the use of the dictionary, if the key value does not exist during access, an error will be reported and the defaultdic
default value can be set. Other functions are the same as the ordinary dictionary dic.
Code:
from collections import defaultdict
def showMessage():
return '没有这个key值'
dd = defaultdict(showMessage) # 传入函数名,可用lambda简化
# dd = defaultdict(lambda: '没有这个key值')
dd['name'] = 'Lisi' # 添加name字段
print (dd['name'])
print (dd['age']) # 打印age字段,没有则返回默认值
result:
Lisi
没有这个key值