Python time、os、random、json、pickle 經常使用模塊1

今日內容:

1、經常使用模塊 2019.04.10 更新

  • 1.time:時間
  • 2.calendar:日曆
  • 3.datetime:能夠運算的時間
  • 4.sys:系統
  • 5.os:操做系統
  • 6.os.path:系統路徑操做
  • 7.random:隨機數
  • 8.json:序列化
  • 9.pickle:序列化

2、經常使用模塊2 2019.04.11 更新

  • 1.shutil:能夠操做權限的處理文件模塊
  • 2.shelve:能夠用字典存取數據到文件
  • 3.標準輸入輸出錯誤流
  • 4.日誌模塊
  • 5.項目開發結構

------1.time模塊------

經常使用的有這幾種方式來表示時間:
    1.時間戳:time.time()
    2.(指定時間戳下的)當前時區時間:time.localtime()
    3.(指定時間戳下的)格林威治時間:time.gmtime()
    4.(指定時間元組下的)格式化時間:time.strftime(fmt[,tupletime])
import time

# 今天(2019.04.10)的時間戳,計算時間是從1970年1月1日開始
print(time.time())  # 1554878880.2359598

# 睡眠或者說,中止運行(實際上是進入循環了)一段時間
time.sleep(seconds)  # time.sleep(2)

# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=14,
# tm_min=53, tm_sec=37, tm_wday=2, tm_yday=100, tm_isdst=0) (一行太長了,手動分兩行)
print(time.localtime())

# 能夠將獲得的時間戳放進參數列表中,能夠格式化返回
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=14,
# tm_min=48, tm_sec=0, tm_wday=2, tm_yday=100, tm_isdst=0)
print(time.localtime(1554878880.2359598))

# 2019-04-10 15:03  按照格式輸出時間樣式
print(time.strftime("%Y-%m-%d %H:%M"))

# 2019-04-10 15:07:04
print(time.strftime("%Y-%m-%d %H:%M:%S"))

# 19-04-10 15:08 Wed
print(time.strftime("%y-%m-%d %H:%M %a"))

# 2019-04-10 03:08 Wednesday
print(time.strftime("%Y-%m-%d %I:%M %A"))

# 2019-04-10 03:10 PM 04/10/19 100 
print(time.strftime("%Y-%m-%d %I:%M %p %x %j "))

# 如下爲格式中規定的關鍵詞格式:
%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 當前時區的名稱
%% %號自己

------2.calendar:日曆------

import calendar

"""
判斷閏年:calendar.isleap(year)
查看某年某月日曆:calendar.month(year, mouth)
查看某年某月起始星期與當月天數:calendar.monthrange(year, mouth)
查看某年某月某日是星期幾:calendar.weekday(year, month, day)
"""
# False
print(calendar.isleap(2018))  # 判斷輸入的年份是否是閏年
# 本身手擼一個
# 分析:能被400整除的年份爲閏年,能爲4整除而且不能爲100整除的也是閏年,其餘的都不是
def my_isleap(num):
    if num % 400 == 0:
        return True
    if num % 4 == 0 and num % 100 != 0:
        return True
    return False

res = my_isleap(2018)
print(res)  # False
print(calendar.month(2018, 10))
"""
# 打印結果以下:
"""
    October 2018
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
"""

------3.datetime:能夠運算的時間------

當前時間:datetime.datetime.now()
昨天:datetime.datetime.now() + datetime.timedelta(days=-1)
修改時間:datetime_obj.replace([...])
格式化時間戳:datetime.date.fromtimestamp(timestamp)


import datetime
# 2019-04-10 15:21:31.775391
print(datetime.datetime.now())  # 直接打印當前時間

# 昨天 2019-04-09 15:23:51.948908
res = datetime.datetime.now() + datetime.timedelta(days=-1)
print(res)

# 當前時間 2019-04-09 15:25:00.728168  其實在上面也被延後了一天了
# 改時間 2018-04-09 15:25:00.728168
res = res.replace(year=2018)
print(res)


# 打印結果:2019-04-10 
res = datetime.date.fromtimestamp(1554878880.2359598)
print(res)

------4.sys:系統------

import sys

# 命令行打印運行程序的路徑
# ['D:/fullstack_07/day17/time時間.py']
print(sys.argv)

# 退出程序,下面的代碼就不會執行了
# print(sys.exit(0))

# 上面的代碼必定要註釋掉啊,否則下面的代碼是不會執行的
# 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32)(後面還有一堆,不復制了)
print(sys.version)

# 最大的數字 9223372036854775807
print(sys.maxsize)
# 其實再大也是能夠,這裏只是設置的一個界限,
# Python3中是以字符串的形式存儲數字
# Python2中有int型和long之分

# ['D:\\fullstack_07\\day17', 'D:\\fullstack_07', ...]
# 環境變量的值
print(sys.path)

# win32 顯示操做系統的平臺名稱
print(sys.platform)

------5.os:操做系統------

import os

# 生成單級目錄
os.mkdir('aaa')

# 生成多級目錄
os.makedirs('aaa/b/c')

# 注意:練習的時候,生成完要註釋代碼,否則會報錯

# 將第一次生成的 aaa 改爲 aa
os.rename('aaa', 'aa')

# 打印當前工做目錄
# D:\fullstack_07\day17
print(os.getcwd())

# 刪除單層空目錄
os.rmdir('aa/b/c')

# 移除多層空目錄
os.removedirs('aa/b')

# 列舉目錄下全部資源
# ['00 今日內容.py', 'time時間.py']
print(os.listdir(r'D:\fullstack_07\day17'))

# 打印的就是: \
# (具備通用性,在不一樣的操做系統下,打印不一樣種的路徑分隔符)
print(os.sep)

# 打印:
# 沒打錯啊,就是一個換行符
res = str(os.linesep)
print(res)

# 打印:;   打印一個分號,能夠用做添加系統環境變量
print(os.pathsep)

# 操做系統名:nt
# 反正我是打印這個,不太懂,後期查了再更新
print(os.name)

# environ({'PROCESSOR_IDENTIFIER':
# 'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel'
# 太長了,就截了前面一小段
print(os.environ)

# 執行shell腳本
# 切換到D盤下
os.system(r'D:\\')

------6.os.path:系統路徑操做------

# D:/fullstack_07/day17/time時間.py
print(__file__)

# 返回path規範化的絕對路徑
# D:\fullstack_07\day17
print(os.path.abspath(r'D:\fullstack_07\day17'))

# 將path分割成目錄和文件名二元組返回
# ('D:\\fullstack_07\\day17', 'time時間.py')
# 至關於rsplit('\') 從右開始對字符串進行切分
res = os.path.split(r'D:\fullstack_07\day17\time時間.py')
print(res)


# 上一級目錄
# D:\fullstack_07\day17
res = os.path.dirname(r'D:\fullstack_07\day17\time時間.py')
print(res)

# 最後一級名稱
#  time時間.py
res = os.path.basename(r'D:\fullstack_07\day17\time時間.py')
print(res)

# 指定路徑是否存在
# True
res30 = os.path.exists(r'D:\fullstack_07\day17\time時間.py')
print(res30)

# 是不是絕對路徑
# True
res31 = os.path.isabs(r'D:\fullstack_07\day17\time時間.py')
print(res31)

# 是不是文件
# True
res32 = os.path.isfile(r'D:\fullstack_07\day17\time時間.py')
print(res32)

# 是不是路徑
# False
res33 = os.path.isdir(r'D:\fullstack_07\day17\time時間.py')
print(res33)

# 路徑拼接
# D:\fullstack_07\time時間.py
# 這樣的好處在於,不一樣系統上的層級關係符號有差別,該方法能夠避免
res34 = os.path.join(r'D:\fullstack_07', 'time時間.py')
print(res34)

# 最後存取時間
# 1554884913.360706  返回時間戳,能夠做爲惟一的標識
res35 = os.path.getatime(r'D:\fullstack_07\day17\time時間.py')
print(res35)

# 最後修改時間
# 1554884977.1773849
res36 = os.path.getmtime(r'D:\fullstack_07\day17\time時間.py')
print(res36)

# 目標大小
# 1168   單位是 字節
res37 = os.path.getsize(r'D:\fullstack_07\common test.py')
print(res37)

# 在Linux和Mac平臺上,該函數會原樣返回path,
# 在windows平臺上會將路徑中全部字符轉換爲小寫,
# 並將全部斜槓轉換爲反斜槓。
# c:\windows\system32\
res38 = os.path.normcase('c:/windows\\system32\\')
print(res38)

# 規範化路徑,如..和/
# c:\windows\Temp
res39 = os.path.normpath('c://windows\\System32\\../Temp/')
print(res39)

------7.random:隨機數------

import random

# 默認隨機產生(0-1)的小數
# 0.6183180335165399
ran1 = random.random()
print(ran1)

# 隨機產生指定範圍的一個整數例:[1,10] 閉區間
# 6
ran2 = random.randint(1, 10)
print(ran2)

# 隨機產生指定範圍的一個整數 例:[1,10) 前閉後開區間
# 3
ran3 = random.randrange(1, 10)
print(ran3)

# 隨機產生指定範圍的一個數 例:(1,10) 開區間
# 1.3022059667107808
rand4 = random.uniform(1, 10)
print(rand4)

# 單例集合 在item中隨機選一個
# 15
item = [1, 'ds', 15, 'we']
rand5 = random.choice(item)
print(rand5)

# 單例集合隨機選擇n個
# ['we', 15]
n = 2
rand6 = random.sample(item, n)
print(rand6)

# 洗牌單列集合
item1 = [1, 'ds', 15, 'we']
# 洗牌後  ['we', 1, 15, 'ds']  
# 洗牌更改的是自身內部元素的位置
# ps: 元組不行,改不了,這個是真的改不了,由於我試了
random.shuffle(item1)
print(item1)

------8.json:序列化------

import json
# json: {} 與 [] 嵌套的數據
# 注:json中的字符串必須所有用 "" 來標識(意思是都得用雙引號,用單引號是不能夠的)

# 序列化:對象 --> 字符串
# 序列化成字符串 :
json_obj = {
    'a': 1,
    'b': 2,
    'c': 'df'
}
js1 = json.dumps(json_obj)
print(js1)

# {"a": 1, "b": 2, "c": "df"}

# 序列化字符串到文件中:

with open('temp.txt', 'w', encoding='utf-8') as f:
    json.dump(json_obj, f)

# 注:字符形式操做
# 反序列化對象:
js2 = json.loads(js1)
print(js2)
# {'c': 'df', 'a': 1, 'b': 2}

# 從文件讀流中反序列化成對象:
with open('temp.txt','r',encoding='utf-8') as f:
    js3 = json.load(f)

print(js3)
# {'a': 1, 'b': 2, 'c': 'df'}

------9.pickle:序列化------

import pickle
"""
序列化:對象 --> 字符串
"""
pickle_obj = {
    'aa': 1,
    'bb': 2,
    'cc': 'df'
}
# 序列化成字符串:
p1 = pickle.dumps(pickle_obj)
print(p1)

# 太長了,隨意切斷的
# b'\x80\x03}q\x00(X\x02\x00\x00\x00aaq
# \x01K\x01X\x02\x00\x00\x00ccq\x02X\x02\x00\x00
# \x00dfq\x03X\x02\x00\x00\x00bbq\x04K\x02u.'

# 序列化字符串到文件中:
with open('temp2.txt', 'wb') as pf:
    pickle.dump(pickle_obj, pf)

# 注:字節形式操做
# 反序列化成對象:
p2 = pickle.loads(p1)
print(p2)
# {'aa': 1, 'bb': 2, 'cc': 'df'}

# 從文件中讀出流數據反序列化成對象
with open('temp2.txt', 'rb') as pf:
    p3 = pickle.load(pf)

print(p3)
# {'cc': 'df', 'bb': 2, 'aa': 1}
相關文章
相關標籤/搜索