第六章 常用模块(2):python常用模块(time,datetime,random)

到上一篇为止,我们对python模块的相关知识做了简单的介绍。 接下来我们介绍一下python常用的模块。

6.3.1 time,datetime模块

  • 用途:
    • 时间的显示
    • 时间的转换
    • 时间的运算
1. time
import time
  1. time.time([secs]) 返回当前时间的时间戳

    时间戳:1970年到当前的秒单位计时器,以前的时间可以用负数指定

  2. time.gmtime([secs]) 将一个时间戳转换为世界标准时区的truct_time(是一个元组,共9个元素 )。

  3. 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)

  4. time.mktime(t) 将一个struct_time转换为时间戳

  5. time.sleep(secs) 线程暂停指定时间,单位秒

  6. time.asctime([t])  
    把一个表示时间的元组或者struct_time表示为:'Sun Oct 1 12:21:11 2018'。如果没有参数,将会将time.localtime()作为参数。

  7. time.ctime([secs]) 把一个时间戳转换成:'Sun Oct 1 12:21:11 2018'。如果没有参数,将会将time.localtime()作为参数。

  8. time.strftime(format[,t]) 把一个表示时间的元组或者struct_time转化为格式化的时间字符串。如果不指定参数t ,将会将time.localtime()作为参数。

    format 的写法可以参考资料
    time.strftime('%Y-%m-%d %H:%M:%S')

  9. time.strptime(string[,format]) 把一个表示时间的字符串 string 转化为struct_time。相当于strftime()的逆向操作。
    time.strftime('%Y-%m-%d %H:%M:%S')

2. datetime

比time模块的接口更加直观,更容易调用

优势:可进行时间运算

import datetime
  1. datetime.date()

  2. datetime.time()

  3. datetime.datetime()

  4. datetime.timedelta()

  5. datetime.replace()

常用方法:

import datetime

d = datetime.datetime.now()  # 取得当前时间的datetime日期类型数据

d + datetime.timedelta(seconds=10)  # 时间的相加,最大单位是天

d.replace(year=2018,month=10)  # 替换时间

6.3.2 random模块

  1. random.randint(a,b) 在a-b之间取随机数,范围包括a和b

    random.randrange(a,b) 与randint()相似,但是范围不包括b

  2. random.random()  
    随机浮点数

  3. random.choice(str) 在给定的字符串里随机返回一个字符

  4. 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)

    ```

  5. 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)
```

猜你喜欢

转载自www.cnblogs.com/py-xiaoqiang/p/11110849.html
今日推荐