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  Locale's abbreviated weekday name.
%A  Locale's full weekday name.
%b  Locale's abbreviated month name.
%B  Locale's full month name.
%c  Locale's appropriate date and time representation.
%I  Hour (12-hour clock) as a decimal number [01,12].
%p  Locale's 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()
原文地址:https://www.cnblogs.com/fansik/p/7679988.html