導入模塊 、標準庫time、random生成隨機驗證碼

 

 

 導入模塊py(文件)出錯時,可追加路徑;導入包相當於執行這個包下的__init__.py文件。

from . import 包名  # 從當前路徑導入

 

import sys,os
print(sys.path)

x=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(x)
print(sys.path) 

 

 

# 標準庫time

import random
import datetime
import time

x1 = time.localtime(123213123)
print(x1)
# print(help(x))
print(x1.tm_year)
print('this is 1973 day:%d' % x1.tm_yday)

# print(time.gmtime())
x = time.localtime()
# print(x.tm_year)
print(" 這是 %d 年的第 %d 天!!" % (x.tm_year, x.tm_yday))

# isdst 夏令時
# time.struct_time(tm_year=2020, tm_mon=3, tm_mday=22, tm_hour=18, \
#  tm_min=53, tm_sec=30, tm_wday =6, tm_yday=82, tm_isdst=0)
# struct_time 元祖形式的 時間;
#  time.time()  獲取時間戳

# 把時間戳轉爲元組
# time.gmtime()   # ,默認傳入UTC的時間戳  ;
time.localtime()   # 默認傳入本地時間;相當於UTC+8時區;

# 把元組轉爲時間戳
# mktime 本地時間——>秒

# 把元組轉爲格式化的字符串
# time.strftime('格式',元組時間)
# time.strftime(" %Y-%m-%d  %H:%M:%S" , x)
print(time.strftime(" %Y-%m-%d  %H:%M:%S", x))  # 2020-03-22  19:17:46

# 把格式化的字符串(與格式對應) 轉爲元組
# time.strptime('格式化的字符串', "格式")
y = time.strptime("2020-03-22  19:18:13", "%Y-%m-%d  %H:%M:%S")
print(y.tm_year)  # 2020

# asctime 元組時間 ——>  字符串
#  ctime  時間戳 ——>字符串


print(time.asctime())  # Sun Mar 22 20:08:37 2020
print(time.ctime())  # Sun Mar 22 20:14:27 2020

print(datetime.datetime.now() + datetime.timedelta(-3))  # 當前時間 -3天

print(random.choices("dddvbgnefghyjukugnh", k=2))   #  ['g', 'u']
print(random.sample('vbgnefghyjuk', k=5))   # ['h', 'g', 'b', 'y', 'n']


def gen_checkcode(k=4):
    # 生成4位 隨機驗證碼
    checkcode = ''
    for i in range(k):
        current = random.randrange(0, 4)  # 猜測與當前的I是否相同;數字
        if current == i:
            tmp = chr(random.randint(65, 90))  # 大寫字母
        else:
            tmp = random.randint(0, 9)  # 數字
        checkcode += str(tmp)

    # print(checkcode)
    return checkcode

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章