Python 的 datetime 模組定義了幾個核心類別:
datetime.date:表示日期,常用屬性為 year、month、day。datetime.time:表示時間,常用屬性為 hour、minute、second、microsecond。datetime.datetime:同時表示日期與時間。datetime.timedelta:表示時間間隔,也就是兩個時間點之間的長度。datetime.tzinfo:與時區相關的資訊(本文不展開,有興趣可查 Python 手冊)。請注意:以上這些物件都是不可變(immutable)的。
date 表示一個日期,由年、月、日組成,建構式如下:
class datetime.date(year, month, day)
參數範圍限制:
MINYEAR 與 MAXYEAR 之間,即 [1, 9999]。date.max、date.min:可表示的最大與最小日期。date.resolution:日期的最小單位。date.today():回傳代表本地今日的 date 物件。date.fromtimestamp(timestamp):由時間戳轉出 date 物件。date.fromordinal(ordinal):將格里高利曆的序數轉為 date 物件。date.year / month / day:年、月、日。date.replace(year, month, day):以新參數產生一個新的日期物件,原物件不變。date.timetuple():回傳對應的 time.struct_time。date.toordinal():回傳對應的格里高利曆序數。date.weekday():週一回傳 0,週二回傳 1,依此類推。date.isoweekday():週一回傳 1,週二回傳 2,依此類推。date.isocalendar():回傳 (year, week, weekday) 形式的元組。date.isoformat():回傳 'YYYY-MM-DD' 字串。date.strftime(fmt):自訂格式化輸出。date2 = date1 + timedelta # 日期加上一段間隔,得到新日期 date2 = date1 - timedelta # 日期減去一段間隔,得到新日期 timedelta = date1 - date2 # 兩個日期相減,得到時間間隔 date1 < date2 # 日期比較
進行日期運算時,務必留意結果不要超出可表示的範圍。
>>> now = date(2012, 2, 24)
>>> tomorrow = now.replace(day=28)
>>> print('now:', now, ', tomorrow:', tomorrow)
now: 2012-02-24 , tomorrow: 2012-02-28
>>> print('timetuple():', now.timetuple())
timetuple(): (2012, 2, 24, 0, 0, 0, 4, 55, -1)
>>> print('weekday():', now.weekday())
weekday(): 4
>>> print('isoweekday():', now.isoweekday())
isoweekday(): 5
>>> print('isocalendar():', now.isocalendar())
isocalendar(): (2012, 8, 5)
>>> print('isoformat():', now.isoformat())
isoformat(): 2012-02-24