1. 程式人生 > >18 python 初學(time、random 模組)

18 python 初學(time、random 模組)

# _author: lily
# _date: 2019/1/13

import time
import datetime

print(help(time))

# print(time.time())   # 1547376144.4092453 時間戳
# time.sleep(3)
# print(time.clock())
# print(time.gmtime())  # 結構化時間 time.struct_time(tm_year=2019, tm_mon=1, tm_mday=13, tm_hour=10, tm_min=48, tm_sec=29, tm_wday=6, tm_yday=13, tm_isdst=0)
print(time.localtime()) # 結構化時間 time.struct_time(tm_year=2019, tm_mon=1, tm_mday=13, tm_hour=18, tm_min=53, tm_sec=1, tm_wday=6, tm_yday=13, tm_isdst=0) print(time.strftime('%Y--%m--%d %H:%M:%S', time.localtime())) # 一定要記下來 print(time.strptime('2019--01--13 18:57:23', '%Y--%m--%d %H:%M:%S')) #把時間再轉回一個結構化的時間
print(time.ctime()) # 把時間轉換成字串格式 Sun Jan 13 19:03:51 2019 print(time.mktime(time.localtime())) # 轉換成時間戳 1547377565.0 print(datetime.datetime.now()) # 2019-01-13 19:07:22.823218

 

random 模組:

# _author: lily
# _date: 2019/1/13

import random

# print(random.random())    # 設定 0 - 1 之間的隨機數
#
print(random.randint(1, 8)) # 包括8 # print(random.choice([123, 'lily', 'su'])) # 隨機取一個元素 # print(random.sample([123, 'lily', 'su'], 2)) # 隨機選取兩個元素 # print(random.randrange(1, 10)) # 不包括10 def v_code(): code = '' for i in range(5): add = random.choice([random.randrange(10), chr(random.randrange(65, 91))]) code += str(add) print(code) v_code() print(chr(90))