datetime模塊提供了簡單和復雜的方式用於操縱日期和時間的類。雖然支持日期和時間運算,但實現的重點是為了輸出格式化和操作高效地提取屬性。
1. 模塊內容
內容 | 描述 |
---|---|
常量 | |
datetime.MINYEAR | date和datetime對象允許的最小年份 |
datetime.MAXYEAR | date和datetime對象允許的最大年份 |
類 | |
datetime.date | 日期對象,屬性(year, month, day) |
datetime.time | 時間對象,屬性(hour, minute, second, microsecond, tzinfo) |
datetime.datetime | 日期時間對象,屬性(date和time屬性組合) |
datetime.timedelta | Difference between two datetime values(原文) |
datetime.tzinfo | 時區信息對象的抽象基類, datetime和time類使用它定制化時間調節 |
2. datetime.date類
date對象表示理想化日歷中的日期(年、月和日), 公歷1年1月1日被稱為第一天,依次往后推。
- 類方法
from datetime import date
print 'today():', date.today() # 返回當前日期對象
print 'fromtimestamp(1491448600):', date.fromtimestamp(1491448600) # 返回時間戳的日期對象
print 'date.fromordinal(1):', date.fromordinal(1) # 返回對應公歷序數的日期對象
# 輸出
today():2017-04-06
fromtimestamp(1491448600):2017-04-06
date.fromordinal(1): 0001-01-01
- 對象方法和屬性
from datetime import date
d = date(2017, 04, 06)
print 'd.year:', d.year # 返回date對象的年份
print 'd.month:', d.month # 返回date對象的月份
print 'd.day:', d.day # 返回date對象的日
print 'd.timetuple():', d.timetuple() # 返回date對象的struct_time結構
print 'd.toordinal():', d.toordinal() # 返回公歷日期的序數
print 'd.weekday():', d.weekday() # 返回一星期中的第幾天,星期一是0
print 'd.isoweekday():', d.isoweekday() # 返回一星期中的第幾天, 星期一1
print 'd.isocalendar():', d.isocalendar() # 返回一個元組(年份, 這一年的第幾周, 周幾)
print 'd.isoformat():', d.isoformat() # 以ISO 8601格式‘YYYY-MM-DD’返回date的字符串形式
print 'd.ctime():', d.ctime() # 返回一個表示日期的字符串
print 'd.strftime("%Y-%m-%d"):', d.strftime("%Y-%m-%d") # 返回指定格式的日期字符串
print 'd.replace(year=2012, month=12) :', d.replace(year=2012, month=12) # 替換
# 輸出
d.year: 2017
d.month: 4
d.day: 6
d.timetuple(): time.struct_time(tm_year=2017, tm_mon=4, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=96, tm_isdst=-1)
d.toordinal(): 736425
d.weekday(): 3
d.isoweekday(): 4
d.isocalendar(): (2017, 14, 4)
d.isoformat(): 2017-04-06
d.ctime(): Thu Apr 6 00:00:00 2017
d.strftime("%Y-%m-%d"): 2017-04-06
d.replace(year=2012, month=12) : 2012-12-06
3. datetime.time類
表示一個(當地)時間對象,與任何特定的日期無關,並且可以通過tzinfo(時區)對象進行調整。
from datetime import time
t = time(12, 10, 30, 50)
print 't.hour:', t.hour # time對象小時數
print 't.minute:', t.minute # time對象分鍾數
print 't.second:', t.second # time對象秒數
print 't.microsecond:', t.microsecond # time對象微秒數
print 't.isoformat():', t.isoformat() # 返回ISO 8601格式的時間字符串
print 't.strftime("%H:%M:%S:%f"):', t.strftime("%H:%M:%S:%f") # 返回指定格式的時間格式
print 't.replace(hour=23, minute=0):', t.replace(hour=23, minute=0) # 替換
# 輸出
t.hour: 12
t.minute: 10
t.second: 30
t.microsecond: 50
t.isoformat(): 12:10:30.000050
t.strftime("%H:%M:%S:%f"): 12:10:30:000050
t.replace(hour=23, minute=0): 23:00:30.000050
4. datetime.datetime類
datetime對象包含date對象和time對象的所有信息
- 類方法
from datetime import datetime, time, date
print 'datetime.today():', datetime.today() # 返回本地當前的時間datetime對象
print 'datetime.now():', datetime.now() # 返回本地當前的日期和時間的datetime對象
print 'datetime.utcnow():', datetime.utcnow() # 返回當前UTC日期和時間的datetime對象
print 'datetime.fromtimestamp(1491468000):', datetime.fromtimestamp(1491468000) # 返回對應時間戳的datetime對象
print 'datetime.fromordinal(699000):', datetime.fromordinal(699000) # 同date.fromordinal類似
print 'datetime.combine(date(2012,12,12), time(12,12,12)):', datetime.combine(date(2012, 12, 12), time(23, 59, 59)) # 拼接date和time
print 'datetime.strptime("2012-12-10", "%Y-%m-%d"):', datetime.strptime("2012-12-10", "%Y-%m-%d") # 將特定格式的日期時間字符串解析成datetime對象
# 輸出
datetime.today(): 2017-04-06 16:53:12.080000
datetime.now(): 2017-04-06 16:53:12.080000
datetime.utcnow(): 2017-04-06 08:53:12.080000
datetime.fromtimestamp(1491468000): 2017-04-06 16:40:00
datetime.fromordinal(699000): 1914-10-19 00:00:00
datetime.combine(date(2012,12,12), time(12,12,12)): 2012-12-12 23:59:59
datetime.strptime("2012-12-10", "%Y-%m-%d"): 2012-12-10 00:00:00
- 對象方法和屬性
from datetime import datetime
d = datetime(2017, 04, 06, 12, 10, 30)
print 'd.date():', d.date() # 從datetime中拆分出date
print 'd.time():', d.time() # 從datetime中拆分出time
print 'd.timetz()', d.timetz() # 從datetime中拆分出具體時區屬性的time
print 'd.replace(year=2016):', d.replace(year=2016) # 替換
print 'd.timetuple():', d.timetuple() # 時間數組,即struct_time結構
print 'd.toordinal():', d.toordinal() # 和date.toordinal一樣
print 'd.weekday():', d.weekday() # 和date.weekday一樣
print 'd.isoweekday():', d.isoweekday() # 和date.isoweekday一樣
print 'd.isocalendar():', d.isocalendar() # 和date.isocalendar一樣
print 'd.isoformat():', d.isoformat() # 同上
print 'd.ctime():', d.ctime() # 同上
print 'd.strftime("%Y/%m/%d %H:%M:%S"):', d.strftime('%Y/%m/%d %H:%M:%S') # 同上
# 輸出
d.date(): 2017-04-06
d.time(): 12:10:30
d.timetz() 12:10:30
d.replace(year=2016): 2016-04-06 12:10:30
d.timetuple(): time.struct_time(tm_year=2017, tm_mon=4, tm_mday=6, tm_hour=12, tm_min=10, tm_sec=30, tm_wday=3, tm_yday=96, tm_isdst=-1)
d.toordinal(): 736425
d.weekday(): 3
d.isoweekday(): 4
d.isocalendar(): (2017, 14, 4)
d.isoformat(): 2017-04-06T12:10:30
d.ctime(): Thu Apr 6 12:10:30 2017
d.strftime("%Y/%m/%d %H:%M:%S"): 2017/04/06 12:10:30
5. datetime.timedelta類
timedelta對象表示一個時間段,即兩個日期 (date) 或日期時間 (datetime) 之間的差。支持參數:weeks、days、hours、minutes、seconds、milliseconds、microseconds。但是據官方文檔說其內部只存儲days、seconds 和 microseconds,其他單位會做對應的時間轉換。
>>>from datetime import timedelta, date, datetime
>>>d = date.today()
>>>print d
2017-04-06
>>>print d - timedelta(days=5) # 計算前5天
2017-04-01
>>>dt = datetime.now()
>>>print dt
2017-04-06 17:51:03.568000
>>>print dt - timedelta(days=1, hours=5) # 計算前1天5小時
2017-04-05 12:51:03.568000
6. 格式字符串
datetime、date、time 都提供了 strftime() 方法,該方法接收一個格式字符串,輸出日期時間的字符串表示。支持的轉換格式如下:
字符 | 含義 | 例子 |
---|---|---|
%a | 英文星期的簡寫 | Sun, Mon, …, Sat |
%A | 英文星期的全拼 | Sunday, Monday, …, Saturday |
%w | 星期幾,星期天為0,星期六為6 | 0, 1, …, 6 |
%d | 這個月的第幾天,以0填充的10進制 | 01, 02, …, 31 |
%b | 月份英文簡寫 | Jan, Feb, …, Dec |
%B | 月份英文全拼 | January, February, …, December |
%m | 月份數,以0填充的10進制 | 01, 02, …, 12 |
%y | 不帶世紀的年份 | 00, 01, …, 99 |
%Y | 帶有世紀的年份 | 1970, 1988, 2001, 2013 |
%H | 24小時制的小時數 | 00, 01, …, 23 |
%I | 12小時制的小時數 | 01, 02, …, 12 |
%p | AM或者PM | AM, PM |
%M | 分鍾 | 00, 01, …, 59 |
%S | 秒數 | 00, 01, …, 59 |
%f | 微秒 | 000000, 000001, …, 999999 |
%z | 與utc時間的間隔 | (), +0000, -0400, +1030 |
%Z | 時區 | (), UTC, EST, CST |
%j | 當年的第幾天 | 001, 002, …, 366 |
%U | 當年的第幾周(星期天作為周的第一天) | 00, 01, …, 53 |
%W | 當年的第幾周(星期一作為周的第一天) | 00, 01, …, 53 |
%c | 日期時間的字符串表示 | Tue Aug 16 21:30:00 1988 |
%X | 時間字符串表示 | 21:30:00 |
%x | 日期字符串表示 | 08/16/88 |
%% | 相當於轉意等於一個% | % |
7. 常見應用
- 時間戳轉日期
>>>from datetime import datetime
>>>timestamp = 1491550000
>>>dt = datetime.fromtimestamp(timestamp)
>>>print dt
2017-04-07 15:26:40
>>>print dt.strftime('%Y-%m-%d')
2017-04-07
- 字符串轉日期
>>>from datetime import datetime
>>>str = '2012-12-10'
>>>dt =datetime.strptime(str, '%Y-%m-%d')
>>>print dt.strftime('%Y/%m/%d')
>>>2012/12/10
- 計算前幾天日期
>>>from datetime import datetime, timedelta
>>>td = datetime.today()
>>>print td
2017-04-07 16:27:52.111000
>>>print dt.strftime('%Y/%m/%d')
2017-04-06 16:27:52.111000