在 Python 處理日期與時間
Max Shron
Data Scientist and Author
date() 類別接受年、月、日作為參數date 物件有存取子如 .year,也有方法如 .weekday()date 物件可像數字一樣比較,可用 min()、max()、sort()date 相減會得到 timedeltadate 物件轉成字串,使用 .isoformat() 或 .strftime() 方法datetime() 類別包含 date() 的所有參數,另加時、分、秒與微秒.replace() 方法替換 datetime 中任一值.total_seconds() 方法將 timedelta 轉成整數.strptime() 把字串轉成日期,用 .strftime() 把日期轉成字串datetime 設了 tzinfo,則為「時區感知」;否則為「時區未知」datetime 對齊 UTC(全球時間標準).replace() 變更 datetime 的時區,同步保留原日期與時間.astimezone() 依新時區調整日期與時間dateutil.tz 提供完整且更新的時區資料庫parse_dates 設為需解析為 datetime 的欄位清單parse_dates 不奏效,改用 pd.to_datetime() 函式.groupby() 分組後可計算每組彙總,如 .first()、.min()、.mean().resample() 依 datetime 欄位按年、月、日等進行分組.tz_localize() 設定時區,日期與時間維持不變.tz_convert() 轉換為新時區所對應的日期與時間在 Python 處理日期與時間