Python基础知识(25):常用内建模块
1、datetime:处理日期和时间
(1)获取当前日期和时间
from datetime import datetime now = datetime.now() print(now) 结果: 2018-12-07 16:05:53.396953
(2)获取指定日期和时间
from datetime import datetime dt = datetime(2019,1,1,00,00) print(dt) 结果: 2019-01-01 00:00:00
(3)datetime转换为timestamp
from datetime import datetime dt = datetime(2019,1,1,00,00) print(dt.timestamp()) 结果: 1546272000.0
timestamp转换为datetime
from datetime import datetime t = 1546272000.0 #本地时间 print(datetime.fromtimestamp(t)) #UTC时间 print(datetime.utcfromtimestamp(t)) 结果: 2019-01-01 00:00:00 2018-12-31 16:00:00
timestamp也可以直接被转换到UTC标准时区的时间
(4)str转换为datetime
from datetime import datetime sday = datetime.strptime(\'2019-1-1 00:00:00\',\'%Y-%m-%d %H:%M:%S\') print(sday) 结果: 2019-01-01 00:00:00
字符串\'%Y-%m-%d %H:%M:%S\'规定了日期和时间部分的格式。详细的说明请参考Python文档
datetime转换为str
from datetime import datetime now = datetime.now() print(now.strftime(\'%a, %b %d %H:%M\')) 结果: Fri, Dec 07 17:08
(5)datetime加减
from datetime import datetime, timedelta now = datetime.now() print(now) m = now + timedelta(2019,1,1,00,00) print(m) s = now - timedelta(minutes=10) print(s) 结果: 2018-12-07 17:18:39.359425 2024-06-17 17:18:40.359426 2018-12-07 17:08:39.359425
(6)本地时间转换为UTC时间
一个datetime类型有一个时区属性tzinfo,但是默认为None,所以无法区分这个datetime到底是哪个时区,除非强行给datetime设置一个时区
from datetime import datetime, timedelta, timezone utc = timezone(timedelta(hours=8)) now = datetime.now() print(now) dt = now.replace(tzinfo=utc) print(dt) 结果: 2018-12-07 17:21:50.152241 2018-12-07 17:21:50.152241+08:00
可以先通过utcnow()拿到当前的UTC时间,再转换为任意时区的时间
from datetime import datetime, timedelta, timezone utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc) print(utc_dt) bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8))) print(bj_dt) 结果: 2018-12-07 09:28:53.515298+00:00 2018-12-07 17:28:53.515298+08:00
2、collection
提供许多有用的集合类
(1)namedtuple
namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素
from collections import namedtuple Person = namedtuple(\'Person\',[\'x\',\'y\']) p = Person(\'Alice\',12) print(p.x) print(p.y) 结果: Alice 12
(2)deque
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈
deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素
from collections import deque q = deque([\'a\',\'b\',\'c\']) q.append(\'more\') q.appendleft(\'h\') print(q) 结果: deque([\'h\', \'a\', \'b\', \'c\', \'more\'])
(3)defaultdict
使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict
from collections import defaultdict dd = defaultdict(lambda: \'error\') dd[\'k1\'] = \'abc\' print(dd[\'k1\']) print(dd[\'k2\']) 结果: abc error
(4)OrderedDict
使用dict时,Key是无序的。如果要保持Key的顺序,可以用OrderedDict
(5)ChainMap
ChainMap可以把一组dict串起来并组成一个逻辑上的dict。ChainMap本身也是一个dict,但是查找的时候,会按照顺序在内部的dict依次查找
(6)Counter
Counter是一个简单的计数器
from collections import Counter o = Counter() for ch in \'This world devours every person and moves on.\': o[ch] = o[ch] + 1 print(o) 结果: Counter({\' \': 7, \'o\': 5, \'e\': 5, \'s\': 4, \'r\': 4, \'d\': 3, \'v\': 3, \'n\': 3, \'T\': 1, \'h\': 1, \'i\': 1, \'w\': 1, \'l\': 1, \'u\': 1, \'y\': 1, \'p\': 1, \'a\': 1, \'m\': 1, \'.\': 1})
3、 64
64是一种用64个字符来表示任意二进制数据的方法,常用于在URL、Cookie、网页中传输少量二进制数据
import 64 a = 64.b64encode(b\'binary\\x00string\') print(a) b = 64.b64decode(b\'YmluYXJ5AHN0cmluZw==\') print(b) 结果: import 64 a = 64.b64encode(b\'binary\\x00string\') print(a) b = 64.b64decode(b\'YmluYXJ5AHN0cmluZw==\') print(b)
4、struct
Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换
(1)struct的pack函数把任意数据类型变成bytes
import struct print(struct.pack(\'>I\',1024)) 结果: b\'\\x00\\x00\\x04\\x00\'
pack的第一个参数是处理指令,\'>I\'的意思是:>表示字节顺序是big-endian,也就是网络序,I表示4字节无符号整数
(2)unpack把bytes变成相应的数据类型
import struct print(struct.unpack(\'>IH\',b\'\\xf0\\xf8\\xf6\\xf0\\x00\\x80\')) 结果: (4042847984, 128)
根据>IH的说明,后面的bytes依次变为I:4字节无符号整数和H:2字节无符号整数
继续阅读与本文标签相同的文章
中国软件评测中心刘冬:物联网安全应引起足够重视
-
阿里云创业孵化事业部总经理李中雨:经阿里巴巴孵化一年,企业成长6-7倍。
2026-05-19栏目: 教程
-
阿里云学生服务器搭建网站(1)-购买阿里云学生服务器
2026-05-19栏目: 教程
-
提高云资源的利用效率,降低阿里云的成本支出
2026-05-19栏目: 教程
-
东方富海董事长陈玮:想要牛市,要大幅提升直投比例。
2026-05-19栏目: 教程
-
一个系统,搞定闲鱼服务端复杂问题告警-定位-快速处理
2026-05-19栏目: 教程
