1. 程式人生 > >Python基礎-時間模塊和radom模塊

Python基礎-時間模塊和radom模塊

day pri cal bsp name pytho style pro dst

時間模塊
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 Locale
s 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模塊