到上一篇为止,我们对python模块的相关知识做了简单的介绍。 接下来我们介绍一下python常用的模块。
import time
time.time([secs]) 返回当前时间的时间戳
时间戳:1970年到当前的秒单位计时器,以前的时间可以用负数指定
time.gmtime([secs]) 将一个时间戳转换为世界标准时区的truct_time(是一个元组,共9个元素 )。
time.localtime([secs])
将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前系统时间为准
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=27, tm_hour=15, tm_min=0, tm_sec=2, tm_wday=3, tm_yday=178, tm_isdst=0)
time.mktime(t) 将一个struct_time转换为时间戳
time.sleep(secs) 线程暂停指定时间,单位秒
time.asctime([t]) ?
把一个表示时间的元组或者struct_time表示为:‘Sun Oct 1 12:21:11 2018‘。如果没有参数,将会将time.localtime()作为参数。
time.ctime([secs]) 把一个时间戳转换成:‘Sun Oct 1 12:21:11 2018‘。如果没有参数,将会将time.localtime()作为参数。
time.strftime(format[,t]) 把一个表示时间的元组或者struct_time转化为格式化的时间字符串。如果不指定参数t ,将会将time.localtime()作为参数。
format 的写法可以参考资料
time.strftime(‘%Y-%m-%d %H:%M:%S‘)
time.strptime(string[,format])
把一个表示时间的字符串 string 转化为struct_time。相当于strftime()的逆向操作。
time.strftime(‘%Y-%m-%d %H:%M:%S‘)
比time模块的接口更加直观,更容易调用
优势:可进行时间运算
import datetime
datetime.date()
datetime.time()
datetime.datetime()
datetime.timedelta()
datetime.replace()
常用方法:
import datetime
d = datetime.datetime.now() # 取得当前时间的datetime日期类型数据
d + datetime.timedelta(seconds=10) # 时间的相加,最大单位是天
d.replace(year=2018,month=10) # 替换时间
random.randint(a,b) 在a-b之间取随机数,范围包括a和b
random.randrange(a,b) 与randint()相似,但是范围不包括b
random.random() ?
随机浮点数
random.choice(str) 在给定的字符串里随机返回一个字符
random.sample(str,n)
随机返回n个字符的列表。
可以用来做验证码:
```python
import random
import string
s = string.ascii_lowercase + string.digits + string.punctuation
a = ‘‘.join(random.sample(s,5))
print(a)
```
random.shuffle() 洗牌。把列表顺序打乱,并重新赋值给列表。返回None
我们也可以更加随机一下:
```python
import random
import string
s = string.ascii_lowercase + string.digits + string.punctuation
s = list(s)
random.shuffle(s)
s = ''.join(s)
a = ''.join(random.sample(s,6))
print(a)
```
第六章 常用模块(2):python常用模块(time,datetime,random)
原文:https://www.cnblogs.com/py-xiaoqiang/p/11110849.html