json模塊,模塊講解——time,datetime,json,os,requests
json模塊,模塊講解——time,datetime,json,os,requests
文章目錄
- time模塊
- datetime模塊
- 數據格式及轉換
- json模塊
- OS模塊
- requests模塊
time模塊
time.sleep(n) : 休息n秒
json模塊?time.time():返回一個從epoch到現在的秒數,epoch:start of time
import time
# 計算時間消耗
print(time.time(), type(time.time()))
# 1652579195.387747 <class 'float'>
time.time()可以用來計算一個程序執行所消耗的時間
# 開始時間
start = time.time()
# dosth (程序)
# 結束時間
end = time.time()
# 花費的時間
cost = end - start
time.ctime():獲取當前時間字符串
# 獲取當前時間(指定時間戳)的字符串
print(time.ctime(), type(time.ctime()))
# Sun May 15 09:51:54 2022 <class 'str'>
time.gmtime(n): 將當前時間戳轉化為時間結構體(秒數 -> 時間結構體(0時區))
end = time.time()
# 將時間戳轉化為時間結構體(元組)
# 0時區的時間
current = time.gmtime(end)
print(current, type(current))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=1, tm_min=55, tm_sec=7, tm_wday=6, tm_yday=135, tm_isdst=0) <class 'time.struct_time'>
print(current.tm_year, current.tm_yday)
# 2022 135
current = time.gmtime(0) # 開始時間的結構體時間
print(current, type(current))
# time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) <class 'time.struct_time'>
python模塊?time.localtime(): 將時間戳轉化為結構體時間
# time.localtime() 將時間戳轉化為結構體時間
# 本地時間
current = time.localtime(end)
print(current, type(current))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=9, tm_min=58, tm_sec=58, tm_wday=6, tm_yday=135, tm_isdst=0) <class 'time.struct_time'>
datetime模塊
獲取datetime模塊的路徑
print(datetime.__file__)
# D:\anaconda3\envs\python3.7\lib\datetime.py
datetime.datetime => 日期時間
# 獲取今天的日期時間
now = datetime.datetime.now()
print(now, type(now))
# 2022-05-15 10:05:31.378419 <class 'datetime.datetime'>
print(now.year)
# 2022
datetime.date(類) =》日期
# 獲取今天的日期
today = datetime.date.today()
print(today, type(today))
# 2022-05-15 <class 'datetime.date'>
print(today.year)
# 2022
java form-data。datetime類型之間可以相減,獲得timedelta(Δt)
import datetime
import timenow = datetime.datetime.now()
time.sleep(1)
now2 = datetime.datetime.now()
result = now2 - now
print(result, type(result))
# 0:00:01.002496 <class 'datetime.timedelta'>
計算n天前的日期
result = datetime.date.today() + datetime.timedelta(days=-n)
# 計算三天前的日期
today = datetime.date.today()
result = today + datetime.timedelta(days=-3)
print(result)
# 2022-05-12today = datetime.datetime.now()
# 計算三天前的日期
result = today + datetime.timedelta(days=-3)
print(result)
# 2022-05-12 10:48:16.842966# 計算一周前的日期
result = today + datetime.timedelta(weeks=-1)
print(result)
# 2022-05-08
# 計算10天后的日期
result = today + datetime.timedelta(days=10)
print(result)
# 2022-05-25
isinstance: 判斷對象是否是指定類型
q = time.localtime()
print(q)
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=10, tm_min=18, tm_sec=41, tm_wday=6, tm_yday=135, tm_isdst=0)# 判斷q是不是元組類型
print(isinstance(q, tuple))
# True
結構體時間是一個元組的格式
數據格式及轉換
爬蟲模塊,
格式化字符串
%Y 年
%m 月
json。%d 日
%H 時
%M 分
%S 秒
from datetime import datetime?1、time.strftime(字符串的格式,時間結構體或元組):時間結構體或元組 -> 字符串
print(time.strftime("%Y/%m/%d", time.localtime()))
# 2022/05/15
print(time.strftime("%Y-%m-%d %H:%M:%S"), time.localtime())
# 2022-05-15 10:22:27
print(time.strftime("%Y/%m/%d %H:%M:%S", (2019, 1, 29, 15, 15, 23, 45, 21, 19)))
# 2019/01/29 15:15:23
2、time.strptime(要轉換的字符串,字符串的格式):時間字符串 -> 返回時間結構體
print(time.strptime("2018/01/29 15:14:39", "%Y/%m/%d %H:%M:%S"))
# time.struct_time(tm_year=2018, tm_mon=1, tm_mday=29, tm_hour=15, tm_min=14, tm_sec=39, tm_wday=0, tm_yday=29, tm_isdst=-1)
print(time.strptime("20220515", "%Y%m%d"))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=135, tm_isdst=-1)
3、將當前時間戳轉化為元組
now = time.time()
print(now)
# 1652670527.4191196
print(time.localtime(now))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=16, tm_hour=11, tm_min=8, tm_sec=47, tm_wday=0, tm_yday=136, tm_isdst=0)
json模塊
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,它是JavaScript的子集,易于人閱讀和編寫。
python json?前端和后端進行數據交互,其實就是JS和Python進行數據交互。
# json => 輕量級數據交換格式 => 字符串
# 不同語言之間數據交換
# list, str, dict =>
# js / java / go / php ......# 前端 <= json => 后端
# 后端 <= json => 后端
python數據類型與json數據類型的映射關系
java.time.localdatetime?json中常用的方法
使用
import jsoninfo = {"name": "cali","score": 100,"test0": False,'test1': None
}
# 將python對象轉為json
result = json.dumps(info)
print(result, type(result))
# {"name": "cali", "score": 100, "test0": false, "test1": null} <class 'str'>
# 將json對象轉為python
result2 = json.loads(result)
print(result2, type(result2))
# {'name': 'cali', 'score': 100, 'test0': False, 'test1': None} <class 'dict'>
info = ["name", "cali", "score", 100, "test0", False, 'test1', None]
result = json.dumps(info)
print(result, type(result))
# ["name", "cali", "score", 100, "test0", false, "test1", null] <class 'str'>
result2 = json.loads(result)
print(result2, type(result2))
# ['name', 'cali', 'score', 100, 'test0', False, 'test1', None] <class 'list'>
OS模塊
文件、文件夾操作
python接口返回json處理、
獲取當前工作目錄
import osprint(os.getcwd())
# E:\scpythonProject\2022_5_15
獲取當前目錄的文件和文件夾
print(os.listdir())
# ['os操作文件目錄.py', 'test', 'time,datetime.py']
刪除文件
os.remove("a.txt6")
os.remove("test/b.txt")
刪除空目錄
os.removedirs("test2")
os.removedirs("test")
# OSError: [WinError 145] 目錄不是空的。: 'test'
不是空目錄會報錯
檢測給出的路徑是否為一個文件(如果路徑不存在,不是文件 =》False)
print(os.path.isfile("E:\scpythonProject\2022_5_15"))
# False
print(os.path.isfile("./test/adfa.img"))
# True
print(os.path.isfile("./test"))
# False
檢測給出的路徑是否為一個目錄
print(os.path.isdir("./test"))
# True
print(os.path.isdir("./test9"))
# False
常用,判斷路徑是否存在
print(os.path.exists("./test0"))
# False
print(os.path.exists("./test"))
# True
將路徑的目錄和文件進行切割
print(os.path.split("/home/swaroop/byte/code/poem.txt"))
# ('/home/swaroop/byte/code', 'poem.txt')# 因為code后面有/,所以可以判斷code為目錄
print(os.path.split("/home/swaroop/byte/code/"))
# ('/home/swaroop/byte/code', '')# 無法判斷code是不是目錄,默認為文件,因為linux中文件可以沒有后綴
print(os.path.split("/home/swaroop/byte/code"))
# ('/home/swaroop/byte', 'code')
分割文件和擴展名
print(os.path.splitext('/home/swaroop/byte/code/poem.txt'))
# ('/home/swaroop/byte/code/poem', '.txt')
獲取文件所在目錄
print(os.path.dirname('/home/swaroop/byte/code/poem.txt'))
# /home/swaroop/byte/code
創建單文件 os.mkdir
os.mkdir("test3")
創建多級目錄文件
os.makedirs("test4/dadf")
練習
查看指定路徑下有哪些文件和文件夾
path = input("請輸入你要查詢的路徑:")
print(os.listdir(path))
requests模塊
requests的功能:提供網絡請求服務
獲取網頁數據(文本瀏覽器),返回一個響應
response = requests.get(url="https://www.baidu.com")
print(response, type(response))
# <Response [200]> <class 'requests.models.Response'>
# 200 => http請求返回結果的狀態碼 =》 ok
輸出網頁的二進制內容
print(response.content)
輸出狀態碼
print(response.status_code)
# 200
輸出文本,自動轉碼
print(response.text)
# 自動將content轉化為str格式 =》 html代碼
# 不建議使用text自動識別 =》 失敗了比較高
HTTP狀態碼
1xx消息——請求已被服務器接收,繼續處理
2xx成功——請求已成功被服務器接收、理解、并接受
3xx重定向——需要后續操作才能完成這一請求
4xx請求錯誤——請求含有詞法錯誤或者無法被執行
5xx服務器錯誤——服務器在處理某個正確請求時發生錯誤
常見狀態代碼、狀態描述、說明:
200 OK //請求成功
400 Bad Request //客戶端請求有語法錯誤,不能被服務器所理解
401 Unauthorized //請求未經授權,這個狀態代碼必須和WWW-Authenticate報頭域一起使用
403 Forbidden //服務器收到請求,但是拒絕提供服務
404 Not Found //請求資源不存在,eg:輸入了錯誤的URL
500 Internal Server Error //服務器發生不可預期的錯誤**503 Server Unavailable //服務器當前不能處理客戶端的請求,一段時間后可能恢復正常
練習
- 獲取這個png數據(https://n.sinaimg.cn/tech/680/w1920h360/20210322/21a9-kmrcukz9247632.png)
- 保存到文件 => 今天日期時間(202205151147.png)
- requests, open, time/datetime
result = requests.get(url="https://n.sinaimg.cn/tech/680/w1920h360/20210322/21a9-kmrcukz9247632.png")
date = datetime.datetime.today().strftime("%Y%m%d%H%M%S")
with open(f"{date}.png", 'wb') as fp:fp.write(result.content)