当前位置: 移动技术网 > IT编程>脚本编程>Python > Python学习之旅(二十六)

Python学习之旅(二十六)

2018年12月08日  | 移动技术网IT编程  | 我要评论

爱出色演员表,安扎克饼干,免费图库

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串起来并组成一个逻辑上的dictchainmap本身也是一个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、base64

base64是一种用64个字符来表示任意二进制数据的方法,常用于在url、cookie、网页中传输少量二进制数据

import base64
a = base64.b64encode(b'binary\x00string')
print(a)
b = base64.b64decode(b'ymluyxj5ahn0cmluzw==')
print(b)

结果:
import base64
a = base64.b64encode(b'binary\x00string')
print(a)
b = base64.b64decode(b'ymluyxj5ahn0cmluzw==')
print(b)

4、struct

python提供了一个struct模块来解决bytes和其他二进制数据类型的转换

(1)structpack函数把任意数据类型变成bytes

import struct
print(struct.pack('>i',1024))

结果:
b'\x00\x00\x04\x00'

pack的第一个参数是处理指令,'>i'的意思是:>表示字节顺序是big-endian,也就是网络序,i表示4字节无符号整数

(2)unpackbytes变成相应的数据类型

import struct
print(struct.unpack('>ih',b'\xf0\xf8\xf6\xf0\x00\x80'))

结果:
(4042847984, 128)

根据>ih的说明,后面的bytes依次变为i:4字节无符号整数和h:2字节无符号整数

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网