Time,Json簡易使用教程
- 1 Time
- 1.1 獲取時間
- 1.2 程序計時
- 2 Json
1 Time
Python中內置了一些與時間處理相關的庫,如time、datatime和calendar庫。其中time庫是Python中處理時間的標準庫,是最基礎的時間處理庫,提供如下功能功:
(1)獲取時間,
(2)程序計時
1.1 獲取時間
程序如果要使用到時間戳: 可以先獲取時間(以秒為單位),然后格式化輸出。
import time
t0 = time.time() # 獲取當前時間戳(從紀元時間-1970年1月1日00:00:00開到當前【local】這一時刻為止的總秒數),浮點數。
t1 = time.localtime() # localtime--將浮點秒數轉換為time.struct_time()格式的當地時, 默認以time()函數獲取的秒數作為參數
t11 = time.localtime(34.54)
t2 = time.gmtime() # globaltime--將浮點秒數轉換為time.struct_time()格式的世界統一時間
t22 = time.gmtime(34.54)
t3 = ctime() # localtime--將浮點秒數轉換為“Sat Jan 13 21:56:34 2018"這種形式
t33 = time.ctime(34.56)
t4 = time.strftime(time.strftime("%Y-%m-%d %H:%M:%S",t1)) # 將time.struct_time()格式化輸為目標格式的字符串, 配合localtime()/gmtime()一起使用
t5 = time.strptime("2018-1-26 12:55:20",'%Y-%m-%d %H:%M:%S') # 將字符串格式的時間 轉化為time.struct_time()格式。
典型應用deno: 輸出文件需要添加一些時間戳
time_stamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
1.2 程序計時
# 計時
start = time.perf_counter() # 返回一個CPU級別的精確時間計數值,單位為秒,由于這個計數值起點不確定,連續調用差值才有意義
# 待計時的代碼
end = time.perf_counter()
const = start -end
# 休眠
sleep(s) # s擬休眠的時間,單位是秒,可以是浮點數
參考博文:python的time庫詳解
2 Json
json 模塊提供了一種很簡單的方式來編碼和解碼JSON數據。 其中四個主要的函數是 json.dump(), json.dumps()與json.load(), json.loads()。
典型應用deno: 字典數據的存儲和讀取
# 文件載入
processed_data_dict_json_file = "xx.json"with open(processed_data_dict_json_file, "r") as f:processed_data_dict = json.load(f)# 文件寫入out_processed_data_dict_json_file = "xxxx.json"with open(processed_data_dict_json_file, "w") as f:json.dump(processed_data_dict, f)
參考博文:json.dump(), json.dumps()與json.load(), json.loads()區別
(參考博文里說的, json.dumps() json.loads()的作用沒有get到)