Python基础-时间模块和radom模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础-时间模块和radom模块相关的知识,希望对你有一定的参考价值。

时间模块
import time # 引入时间模块
print(time.time()) # 1508146954.9455004: 时间戳
print(time.clock()) # 计算CPU执行时间
print(time.gmtime()) # UTC时间
print(time.localtime()) # 本地时间
print(time.strftime("%Y-%m-%d %H:%M:%S"))
%Y  Year with century as a decimal number.
%m  Month as a decimal number [01,12].
%d  Day of the month as a decimal number [01,31].
%H  Hour (24-hour clock) as a decimal number [00,23].
%M  Minute as a decimal number [00,59].
%S  Second as a decimal number [00,61].
%z  Time zone offset from UTC.
%a  Locales abbreviated weekday name.
%A  Locales full weekday name.
%b  Locales abbreviated month name.
%B  Locales full month name.
%c  Locales appropriate date and time representation.
%I  Hour (12-hour clock) as a decimal number [01,12].
%p  Locales equivalent of either AM or PM.

print(time.strftime("%Y-%m-%d %H:%M:%S%z"))
执行结果:
2017-10-16 18:17:39
fansik = time.strptime(2017-10-16 18:16:26,"%Y-%m-%d %H:%M:%S")

print(fansik)
执行结果:
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=16, tm_hour=18, tm_min=16, tm_sec=26, tm_wday=0, tm_yday=289, tm_isdst=-1)

print(fansik.tm_year)
执行结果:
2017

import datetime
print(datetime.datetime.now())
执行结果:
2017-10-16 18:27:03.256569

random模块

import random
print(random.random()) # 0到1的随机数:0.06054267487515341
print(random.randint(1, 9999)) # 1到9999的随机数,包含1和9999
print(random.randrange(1, 9999)) # 1到9999的随机数,不包含9999
print(random.choice(fansik)) # 随机fansik中的一个字符
print(random.choice([fansik, fanjinbao, zhangsan])) # 随机这三个名字
print(random.sample([fansik, zhangsan, fanjinbao, lisi], 2)) # 随机选两个名字

随机验证码:
import random
def v_code():
    code = ‘‘
    for i in range(5):
        add = random.choice([random.randrange(10), chr(random.randrange(65, 91))])
        # if i == random.randint(0, 4):
        #     add = random.randrange(10)
        # else:
        #     add = chr(random.randrange(65, 91))
        code += str(add)
    print(code)
v_code()

 

以上是关于Python基础-时间模块和radom模块的主要内容,如果未能解决你的问题,请参考以下文章

Python基础之包与模块

python常用模块基础

python3.3不自带的模块或工具包 下载以后要怎么处理才能在开发环境中调用 (比如放到pyth

python基础学习日志day5---os模块

爬虫-request和BeautifulSoup模块

python MultiProcessing模块进程间通信的解惑与回顾