1. 程式人生 > >Python常用模組datetime,logging

Python常用模組datetime,logging

datetime

- 處理時間和日期的標準庫
- 時間戳:從1970年1月1日0時0分0秒,到當前時間的秒數,是浮點數,精確到毫秒
- 模組:
	- date	
	- time
	- datetime
	- timedelta	

date

- 日期物件,常用屬性:year,month,day
from datetime import date
#date 時間物件
d = date(2018,3,16)	#年月日必須是整數
print(d)	#2018-3-16
print(type(d))		#<class 'datetime.date'>

time

- 時間物件,常用屬性:hour,minute,second,microsecond
from datetime import time
#時間物件
t = time(hour=23,minute=45,second=23,microsecond=100)		
#時分秒,可以省略
print(t,type(t))		#23:45:23.00100 <class'datetime.time>

datetime

- 日期時間物件
from datetime import datetime
#日期時間物件
dt = datetime(2018,11,14)	#年月日必須給,整數
print(dt,type(dt))	#2018-11-14 00:00:00 <class'datetime.datetime'>

timedelta

-時間間隔,計算兩個時間之間的長度
from datetime import timedelta
td = datetime(days=1.2)	#可以用浮點數
print(td,type(td))	#1 day,4:48:00 <class'datetime.timedelta'>

datetime日期時間物件常用方法

時間轉換,不同格式轉換
from datetime import datetime
#獲取當前時間
now = datetime.now()
print(now) #2018-11-23 15:28:12.345534
#now型別是datetime物件,不是字串
#datetime轉成字串輸出
time_str = now.strftime(’%Y-%m-%d %H:%M:%S’)
print(time_str,type(time_str))
#2018-11-23 15:34:45 <class’str’>
#時間str轉成datetime
dt = datetime.strptime(“2018/11/23”,"%Y/%m/%d")
print(dt,type(dt))
#2018-11-23 00:00:00 <class’datetime.datetime’>
#datetime物件轉時間戳
print(now.timestamp()) #1542382332.37289
#浮點數,表示從1970-1-1 00:00:00到現在經過多少秒
#時間戳到datetime
dt1 = datetime.fromtimestamp(1542382332.37289)
print(dt1,type(dt1))
#2018-11-23 15:42:32.372890 <class’datetime.datetime’>
date,time,datetime都是不可變物件
print({now:“xianzai”}) #不可變物件才能做鍵
時間格式化:主要針對字串
去看time模組中,time.strftime函式裡的註釋
import time
time.strftime #Ctrl+滑鼠左鍵點time.strftime
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale’s abbreviated weekday name. #周幾的簡寫如Sun
%A Locale’s full weekday name. #周幾的全寫如Sunday
%b Locale’s abbreviated month name. #月份的簡寫如Mon
%B Locale’s full month name. #月份的全寫如Monday
%c Locale’s appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale’s equivalent of either AM or PM.
時間運算
from datetime import datetime,timedelta
today = datetime.now().date()
tomorrow = today + timedelta(days=1) #一天以後
yesterday = today - timedelta(days=1,hours=1.3)
#一天以前,1.3小時以前
print(tomorrow,type(tomorrow))
print(yesterday,type(yesterday))

logging

log日誌logging內建的日誌模組
	程式執行狀況
	資訊,錯誤,警告,錯誤排查,系統運維

簡單使用 只是print,沒有儲存
import logging
logging.debug(“this is a debug log”)
logging.info(“this is a ingo log”)
logging.warning(“this is a warning log”)
logging.error(“this is a error log”)
logging.critical(“this is a critical log”)
日誌級別
debug 除錯,診斷
info 普通訊息
warning 警告資訊
error 錯誤資訊
critical 危險資訊,嚴重錯誤,程式無法繼續執行
logging.basicConfig(level=logging.DEBUG)
import logging
logging.basicConfig(
level=10, #設定級別,根據級別顯示
format="%(asctime)s-%(levelname)s-%(message)s", #設定輸出格式
filename = “test.log”, #設定 日誌檔案路徑,輸出到檔案不列印了
)
logging.debug(“this is a debug log”)
logging.info(“this is a ingo log”)
logging.warning(“this is a warning log”)
logging.error(“this is a error log”)
logging.critical(“this is a critical log”)

格式化
輸出格式
找課件
輸出到檔案
設定一下filename,看原始碼
高階用法:輸出到不同地方

使用步驟:
建立一個logger物件,設定全域性等級
建立handler,決定把日誌發的到那裡(可以有多個),並設定其等級
建立輸出格式,新增到handler
handler新增到logger
#logging的高階用法
import logging
#1 建立一個logger
logger = logging.getLogger("%s_log"%name)
#2 設定日誌等級
logger.setLevel(logging.INFO) #全域性 不設定 預設是warning
#3 建立一個handler物件,用於寫入到日誌檔案
fh = logging.FileHandler(“test.log”,encoding=“utf-8”)
#設定等級
fh.setLevel(logging.INFO)
#建立一個handler物件,用於輸出到控制檯
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
#4 設定格式
formatter = logging.Formatter("%(asctime)s-%(filename)s[line:%(lineno)d-%(levelname)s:%(message)s]")
#hamdler新增格式
fh.setFormatter(formatter)
ch.setFormatter(formatter)
#5 新增handler
logger.addHandler(ch)
logger.addHandler(fh)
#日誌器,我們搞好了
logger.info(“我是一個普通訊息”)
#此資訊在日誌資訊裡,執行不顯示
#2018-11-27 10:07:13,565-test.py[line:51-INFO:我是一個普通訊息]
logger.warning(“This is a warning log”)
#2018-11-27 10:07:13,566-test.py[line:52-WARNING:This is a warning log]