《Python》經常使用內置模塊

1、time模塊(時間模塊)

    三種格式:node

      一、時間戳時間(timestamp):浮點數,秒爲單位,從1970年1月1日0時距今的時間python

          1970.1.1  0:0:0  英國倫敦時間(開始時間)shell

          1970.1.1  8:0:0  北京時間(東8區)dom

      二、結構化時間(struct_time): 元組(tm_year(年),tm_mon(月),tm_mday(日),tm_hour(時),tm_min(分),tm_sec(秒),tm_wday(周幾,0表示週一),tm_yday(一年中第幾天),tm_isdst(是否夏令時))          ide

      三、格式化時間(Format String):  str數據類型  ‘’2018-9-4‘’函數

%y 兩位數的年份表示(00-99%Y 四位數的年份表示(000-9999%m 月份(01-12%d 月內中的一天(0-31%H 24小時制小時數(0-23%I 12小時制小時數(01-12%M 分鐘數(00=59%S 秒(00-59%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天爲星期的開始
%w 星期(0-6),星期天爲星期的開始
%W 一年中的星期數(00-53)星期一爲星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號自己
Python中時間日期格式化符號

 

# 導入時間模塊
import time

# 時間戳
print(time.time())
# 1536045748.757072

# 格式化時間字符串
print(time.strftime('%Y-%m-%d %X'))
# 2018-09-04 15:26:06
print(time.strftime('%Y-%m-%d %H:%M:%S'))
# 2018-09-04 15:26:06

# 結構化時間
print(time.localtime())
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=15, tm_min=28, tm_sec=0, tm_wday=1, tm_yday=247, tm_isdst=0)

 

   小結:時間戳是計算機可以識別的時間;格式化時間是人可以看懂的時間;結構化時間則是用來操做時間的ui

幾種格式之間的轉換:spa

 

 時間戳轉換成結構化時間:操作系統

import time
# 時間戳-->結構化時間
#time.gmtime(時間戳)    #UTC時間,與英國倫敦當地時間一致
#time.localtime(時間戳) #當地時間。例如咱們如今在北京執行這個方法:與UTC時間相差8小時,UTC時間+8小時 = 北京時間
print(time.gmtime(1500000000))
# time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
print(time.localtime(1500000000))
# time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)

# 結構化時間-->時間戳
# time.mktime(結構化時間)
time_tuple = time.localtime(1500000000)
print(time_tuple)
# time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
print(time.mktime(time_tuple))
# 1500000000.0

 

格式化時間與結構化時間互相轉換:命令行

import time

# 結構化時間-->格式化時間
# time.strftime('格式定義','結構化時間') 結構化時間參數若不傳,則顯示當前時間
print(time.strftime('%Y-%m-%d %X'))
# 2018-09-04 16:09:14
print(time.strftime('%Y-%m-%d %X',time.localtime(1500000000)))
# 2017-07-14 10:40:00

# 格式化時間-->結構化時間
# time.strptime(格式化時間字符串,字符串對應的格式)
print(time.strptime('2018-9-4', '%Y-%m-%d'))
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=247, tm_isdst=-1)
print(time.strptime('9/4/2018','%m/%d/%Y'))
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=247, tm_isdst=-1)

 

 

 時間戳轉換成格式化時間:

import time

# 結構化時間--> %a %b %d %H:%M:%S %Y
# time.asctime(結構化時間) 若是不傳參數,直接返回當前時間的格式化串
print(time.asctime(time.localtime(1500000000)))
# Fri Jul 14 10:40:00 2017
print(time.asctime())
# Tue Sep  4 16:26:10 2018

# 時間戳--> %a %b %d %H:%M:%S %Y
# time.ctime(時間戳) 若是不傳參數,直接返回當前時間的格式化串
print(time.ctime())
# Tue Sep  4 16:29:00 2018
print(time.ctime(1500000000))
# Fri Jul 14 10:40:00 2017

 

 

import time

t1 = time.mktime(time.strptime('2017-5-1 11:13:44','%Y-%m-%d %H:%M:%S'))
t2 = time.mktime(time.strptime('2018-9-4 16:33:01','%Y-%m-%d %H:%M:%S'))
t3 = t2 - t1
struct_time = time.gmtime(t3)
print('過去了%d年%d月%d天%d小時%d分鐘%d秒' % (struct_time.tm_year-1970,struct_time.tm_mon-1,
                                       struct_time.tm_mday-1,struct_time.tm_hour,
                                       struct_time.tm_min,struct_time.tm_sec))
# 過去了1年4月6天5小時19分鐘17秒
計算時間差
# 寫函數,計算本月1號的時間戳時間
import time
def get_timestamp():
    fmt_time = time.strftime('%Y-%m-1') # 本月1號
    struct = time.strptime(fmt_time,'%Y-%m-%d')
    res = time.mktime(struct)
    return res
print(get_timestamp())
# 1535731200.0
計算本月1號的時間戳時間

 

 

2、random模塊(隨機數模塊)    

import random

# 取隨機整數
print(random.randint(1,10))         # 1-10都能取
print(random.randrange(1,10))       # 只能取1-9,取不到10
print(random.randrange(1,100,2))    # 1-99的奇數
print(random.randrange(2,100,2))    # 2-99的偶數

# 取隨機小數
print(random.random())      # 0-1之間的浮點數
print(random.uniform(1,10)) # 1-10之間的浮點數

# 從一個列表中隨機抽取
lst = [1,2,3,4,5,('a','b'),'cc','dd']
print(random.choice(lst))           # 以列表裏的每一個元素爲單位取
print(random.choice(range(100)))    # 0-99的列表中取一個值
print(random.sample(lst,3))         # 列表中隨機取3個元素

# 亂序
lst = [1,2,3,4,5,('a','b'),'cc','dd']
random.shuffle(lst)
print(lst)  # 在原有列表的基礎上打亂順序,不產生新列表

 

 

import random

# 6位數字驗證碼
def get_code(n=6):
    code = ''
    for i in range(n):
        num = random.randint(0,9)
        code += str(num)
    return code
ret1 = get_code()   # 默認6位
ret2 = get_code(4)  # 改爲4位
print(ret1,ret2)    # 265326 1548

# 6位驗證碼,包含數字,大小寫字母
def get_code(n=6):
    code = ''
    for i in range(n):
        num = str(random.randint(0,9))
        alpha_upper = chr(random.randint(65,90))    # 大寫字母的ascii碼是65-90
        alpha_lower = chr(random.randint(97,122))   # 小寫字母的ascii碼是97-122
        c = random.choice([num,alpha_upper,alpha_lower])
        code += c
    return code
ret1 = get_code()
ret2 = get_code(4)
print(ret1,ret2)    # P9njz1 12Hw

# 6位驗證碼,包含數字,大小寫字母(可純數字)
def get_code(n = 6,alph_flag = True):
    code = ''
    for i in range(n):
        c = str(random.randint(0,9))
        if alph_flag:
            alpha_upper = chr(random.randint(65, 90))
            alpha_lower = chr(random.randint(97, 122))
            c = random.choice([c,alpha_upper,alpha_lower])
        code += c
    return code
ret1 = get_code()           # 默認6位數字大小寫字母組成
ret2 = get_code(6,False)    # 6位純數字
ret3 = get_code(4,False)    # 4位純數字
print(ret1,ret2,ret3)       # wn27w4 808732 1524
生成隨機驗證碼

 

 

3、os模塊

    os模塊是與操做系統交互的一個接口

import os

# 文件和文件夾的操做
os.remove()                        # 刪除一個文件
os.rename("oldname","newname")     # 重命名文件/目錄

os.mkdir('dirname')                # 相對路徑下生成單級目錄;至關於shell中mkdir dirname
os.makedirs('dirname1/dirname2')   # 相對路徑下生成多級目錄
os.rmdir('dirname')                # 刪除單級空目錄,若目錄不爲空則沒法刪除,報錯;至關於shell中rmdir dirname
os.removedirs('dirname1/dirname2') # 若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推

os.listdir('D:\python')            # 列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印
os.stat('path/filename')           # 獲取文件/目錄信息

# 執行操做系統命令
os.system(命令)                     # 運行shell命令,直接顯示
os.popen(命令).read()               # 運行shell命令,獲取執行結果

# 和Python程序的工做目錄相關的
os.getcwd()                        # 獲取當前工做目錄,即當前python腳本工做的目錄路徑
os.chdir("dirname")                # 改變當前腳本工做目錄;至關於shell下cd

# os.path系列(路徑的操做)
path = 'D:/python/day23/day23.py'
os.path.join('D:/python','day23')  # 將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略
os.path.split(path)                # 將path分割成目錄和文件名二元組返回
os.path.dirname(path)              # 返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path)             # 返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
os.path.exists(path)               # 若是path存在,返回True;若是path不存在,返回False
os.path.isfile(path)               # 若是path是一個存在的文件,返回True。不然返回False
os.path.isdir(path)                # 若是path是一個存在的目錄,則返回True。不然返回False
os.path.abspath(path)              # 返回path規範化的絕對路徑
os.path.getsize(path)              # 返回path的大小
os.path.isabs(path)                # 若是path是絕對路徑,返回True
os.path.getatime(path)             # 返回path所指向的文件或者目錄的最後訪問時間
os.path.getmtime(path)             # 返回path所指向的文件或者目錄的最後修改時間

# __file__文件中的一個內置變量,描述的是這個文件的絕對路徑

 

 

stat 結構:

st_mode: inode 保護模式
st_ino: inode 節點號。
st_dev: inode 駐留的設備。
st_nlink: inode 的連接數。
st_uid: 全部者的用戶ID。
st_gid: 全部者的組ID。
st_size: 普通文件以字節爲單位的大小;包含等待某些特殊文件的數據。
st_atime: 上次訪問的時間。
st_mtime: 最後一次修改的時間。
st_ctime: 由操做系統報告的"ctime"。在某些系統上(如Unix)是最新的元數據更改的時間,在其它系統上(如Windows)是建立時間(詳細信息參見平臺的文檔)。
stat 結構:

 

os.sep    輸出操做系統特定的路徑分隔符,win下爲"\\",Linux下爲"/"
os.linesep    輸出當前平臺使用的行終止符,win下爲"\r\n",Linux下爲"\n"
os.pathsep    輸出用於分割文件路徑的字符串 win下爲;,Linux下爲:
os.name    輸出字符串指示當前使用平臺。win->'nt'; Linux->'posix'
os模塊的屬性

 

 

4、sys模塊

     sys模塊是與Python解釋器交互的一個接口

import sys

sys.argv           # 命令行參數List,第一個元素是程序自己路徑
sys.exit(n)        # 退出程序,正常退出時exit(0),錯誤退出sys.exit(1)
sys.version        # 獲取Python解釋程序的版本信息
sys.platform       # 返回操做系統平臺名稱
sys.modules        # 查看當前內存空間中全部的模塊,和這個模塊的內存空間

sys.path           # 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
# 一個模塊可否被導入,就看這個模塊所在的目錄在不在sys.path路徑中 # 內置模塊和第三方擴展模塊都不須要咱們處理sys.path就能夠直接使用 # 自定義的模塊的導入工做須要本身手動的修改sys.path

 

import sys
try:
    sys.exit(1)
except SystemExit as e:
    print(e)
異常處理和status
相關文章
相關標籤/搜索