本文轉載自腳本之家,源網址為:https://www.jb51.net/article/147429.htm
一、Python中日期時間模塊datetime介紹
(一)、datetime模塊中包含如下類:
類名功能說明
| date | 日期對象,常用的屬性有year, month, day |
| time | 時間對象 |
| datetime | 日期時間對象,常用的屬性有hour, minute, second, microsecond |
| datetime_CAPI | 日期時間對象C語言接口 |
| timedelta | 時間間隔,即兩個時間點之間的長度 |
| tzinfo | 時區信息對象 |
(二)、datetime模塊中包含的常量
常量功能說明用法返回值
| MAXYEAR | 返回能表示的最大年份 | datetime.MAXYEAR | 9999 |
| MINYEAR | 返回能表示的最小年份 | datetime.MINYEAR | 1 |
二、date類
(一)、date對象構成
1、date對象由year年份、month月份及day日期三部分構成:
?
2、 通過year,?month,?day三個數據描述符可以進行訪問:
?
| 1 2 3 4 5 6 7 8 9 | >>> a = datetime.date.today() >>> a datetime.date(2017, 3, 22) >>> a.year 2017 >>> a.month 3 >>> a.day 22 |
3、當然,你也可以用__getattribute__(...)方法獲得上述值:
?
| 1 2 3 4 5 6 | >>> a.__getattribute__('year') 2017 >>> a.__getattribute__('month') 3 >>> a.__getattribute__('day') 22 |
(二)、date對象中包含的方法與屬性
1、用于日期比較大小的方法
方法名方法說明用法
| __eq__(…) | 等于(x==y) | x.__eq__(y) |
| __ge__(…) | 大于等于(x>=y) | x.__ge__(y) |
| __gt__(…) | 大于(x>y) | x.__gt__(y) |
| __le__(…) | 小于等于(x<=y) | x.__le__(y) |
| __lt__(…) | 小于(x | x.__lt__(y) |
| __ne__(…) | 不等于(x!=y) | x.__ne__(y) |
以上方法的返回值為True\False?
示例如下:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> a=datetime.date(2017,3,1) >>> b=datetime.date(2017,3,15) >>> a.__eq__(b) False >>> a.__ge__(b) False >>> a.__gt__(b) False >>> a.__le__(b) True >>> a.__lt__(b) True >>> a.__ne__(b) True |
2、獲得二個日期相差多少天
使用__sub__(...)和__rsub__(...)方法,其實二個方法差不太多,一個是正向操作,一個是反向操作:
方法名方法說明用法
| __sub__(…) | x - y | x.__sub__(y) |
| __rsub__(…) | y - x | x.__rsub__(y) |
示例如下:
?
| 1 2 3 4 5 6 7 8 | >>> a datetime.date(2017, 3, 22) >>> b datetime.date(2017, 3, 15) >>> a.__sub__(b) datetime.timedelta(7) >>> a.__rsub__(b) datetime.timedelta(-7) |
計算結果的返回值類型為datetime.timedelta, 如果獲得整數類型的結果則按下面的方法操作:
?
| 1 2 3 4 | >>> a.__sub__(b).days 7 >>> a.__rsub__(b).days -7 |
3、ISO標準化日期
如果想要讓所使用的日期符合ISO標準,那么使用如下三個方法:?
1).*?isocalendar(...)*:返回一個包含三個值的元組,三個值依次為:year年份,week number周數,weekday星期數(周一為1…周日為7):?
示例如下
?
| 1 2 3 4 5 6 7 8 9 | >>> a = datetime.date(2017,3,22) >>> a.isocalendar() (2017, 12, 3) >>> a.isocalendar()[0] 2017 >>> a.isocalendar()[1] 12 >>> a.isocalendar()[2] 3 |
2).?isoformat(...): 返回符合ISO 8601標準 (YYYY-MM-DD) 的日期字符串;?
示例如下
?
| 1 2 3 | >>> a = datetime.date(2017,3,22) >>> a.isoformat() '2017-03-22' |
3).?isoweekday(...): 返回符合ISO標準的指定日期所在的星期數(周一為1…周日為7)?
示例如下:
?
| 1 2 3 | >>> a = datetime.date(2017,3,22) >>> a.isoweekday() 3 |
4).與isoweekday(...)相似的還有一個weekday(...)方法,只不過是weekday(...)方法返回的周一為 0, 周日為 6?
示例如下:
?
| 1 2 3 | >>> a = datetime.date(2017,3,22) >>> a.weekday() 2 |
4、其他方法與屬性
1).?timetuple(...):該方法為了兼容time.localtime(...)返回一個類型為time.struct_time的數組,但有關時間的部分元素值為0:
?
| 1 2 3 4 5 6 7 8 9 | >>> a = datetime.date(2017,3,22) >>> a.timetuple() time.struct_time(tm_year=2017, tm_mon=3, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=81, tm_isdst=-1) >>> a.timetuple().tm_year 2017 >>> a.timetuple().tm_mon 3 >>> a.timetuple().tm_mday 22 |
2).toordinal(...): 返回公元公歷開始到現在的天數。公元1年1月1日為1
?
| 1 2 3 | >>> a = datetime.date(2017,3,22) >>> a.toordinal() 736410 |
3).?replace(...):返回一個替換指定日期字段的新date對象。參數3個可選參數,分別為year,month,day。注意替換是產生新對象,不影響原date對象。
?
| 1 2 3 4 5 6 | >>> a = datetime.date(2017,3,22) >>> b = a.replace(2017,2,28) >>> a datetime.date(2017, 3, 22) >>> b datetime.date(2017, 2, 28) |
4).resolution:date對象表示日期的最小單位。這里是天。
?
| 1 2 | >>> datetime.date.resolution datetime.timedelta(1) |
5).fromordinal(...):將Gregorian日歷時間轉換為date對象;Gregorian Calendar :一種日歷表示方法,類似于我國的農歷,西方國家使用比較多。
?
| 1 2 3 4 | >>> a = datetime.date(2017,3,22) >>> b = a.toordinal() >>> datetime.date.fromordinal(b) datetime.date(2017, 3, 22) |
6).fromtimestamp(...):根據給定的時間戮,返回一個date對象
?
| 1 2 3 4 | >>> time.time() 1490165087.2242179 >>> datetime.date.fromtimestamp(time.time()) datetime.date(2017, 3, 22) |
7).today(...):返回當前日期
?
| 1 2 | >>> datetime.date.today() datetime.date(2017, 3, 22) |
8).max: date類能表示的最大的年、月、日的數值
?
| 1 2 | >>> datetime.date.max datetime.date(9999, 12, 31) |
9).min: date類能表示的最小的年、月、日的數值
?
| 1 2 | >>> datetime.date.min datetime.date(1, 1, 1) |
(三)、日期的字符串輸出
1、如果你想將日期對象轉化為字符串對象的話,可以用到__format__(...)方法以指定格式進行日期輸出:
?
| 1 2 3 4 5 6 7 8 9 | >>> a = datetime.date(2017,3,22) >>> a.__format__('%Y-%m-%d') '2017-03-22' >>> a.__format__('%Y/%m/%d') '2017/03/22' >>> a.__format__('%y/%m/%d') '17/03/22' >>> a.__format__('%D') '03/22/17' |
與此方法等價的方法為strftime(...)
?
| 1 2 | >>> a.strftime("%Y%m%d") '20170322' |
關于格式化字符串的相關內容,請查閱本文最后的:附錄:python中時間日期格式化符號?
2、如果只是相簡單的獲得日期的字符串,則使用__str__(...)
?
| 1 2 | >>> a.__str__() '2017-03-22' |
3、如果想要獲得ctime樣式的格式請使用ctime(...):
?
| 1 2 | >>> a.ctime() 'Wed Mar 22 00:00:00 2017' |
三、time類
(一)、time類的數據構成
time類由hour小時、minute分鐘、second秒、microsecond毫秒和tzinfo五部分組成
?
| 1 | time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) |
相應的,time類中就有上述五個變量來存儲應該的值:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 | >>> a = datetime.time(12,20,59,899) >>> a datetime.time(12, 20, 59, 899) >>> a.hour 12 >>> a.minute 20 >>> a.second 59 >>> a.microsecond 899 >>> a.tzinfo |
與date類一樣,time類也包含__getattribute__(...)方法可以讀取相關屬性:
?
| 1 2 3 4 5 6 | >>> a.__getattribute__('hour') 12 >>> a.__getattribute__('minute') 20 >>> a.__getattribute__('second') 59 |
(二)、time類中的方法和屬性
1、python比較時間大小
相關方法包括:__eq__(...),?__ge__(...),?__gt__(...),?__le__(...),?__lt__(...),?__ne__(...)?
這里的方法與date類中定義的方法大同小異,使用方法與一樣,這里就不過多介紹了,示例如下:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> a = datetime.time(12,20,59,899) >>> b = datetime.time(11,20,59,889) >>> a.__eq__(b) False >>> a.__ne__(b) True >>> a.__ge__(b) True >>> a.__gt__(b) True >>> a.__le__(b) False >>> a.__lt__(b) False |
2、__nonzero__(...)
判斷時間對象是否非零,返回值為True/False:
?
| 1 2 3 | >>> a = datetime.time(12,20,59,899) >>> a.__nonzero__() True |
3、其他屬性
1)、max:最大的時間表示數值:
?
| 1 2 | >>> datetime.time.max datetime.time(23, 59, 59, 999999) |
2)、min:最小的時間表示數值
?
| 1 2 | >>> datetime.time.min datetime.time(0, 0) |
3)、resolution:時間間隔單位為分鐘
?
| 1 2 | >>> datetime.time.resolution datetime.timedelta(0, 0, 1) |
(三)、時間的字符串輸出
1、如果你想將時間對象轉化為字符串對象的話,可以用到__format__(...)方法以指定格式進行時間輸出:
?
| 1 2 3 | >>> a = datetime.time(12,20,59,899) >>> a.__format__('%H:%M:%S') '12:20:59' |
與此方法等價的方法為strftime(...)
?
| 1 2 3 | >>> a = datetime.time(12,20,59,899) >>> a.strftime('%H:%M:%S') '12:20:59' |
關于格式化字符串的相關內容,請查閱本文最后的:附錄:python中時間日期格式化符號?
2、ISO標準輸出
如果要使輸出的時間字符符合ISO標準,請使用isoformat(...):
?
| 1 2 3 | >>> a = datetime.time(12,20,59,899) >>> a.isoformat() '12:20:59.000899' |
3、如果只是相簡單的獲得時間的字符串,則使用__str__(...)
?
| 1 2 3 | >>> a = datetime.time(12,20,59,899) >>> a.__str__() '12:20:59.000899' |
四、datetime類
(一)、datetime類的數據構成
datetime類其實是可以看做是date類和time類的合體,其大部分的方法和屬性都繼承于這二個類,相關的操作方法請參閱,本文上面關于二個類的介紹。其數據構成也是由這二個類所有的屬性所組成的。
?
| 1 | datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) |
(二)、專屬于datetime的方法和屬性
1、 date(…):返回datetime對象的日期部分:
?
| 1 2 3 4 5 | >>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>> a.date() datetime.date(2017, 3, 22) |
2、time(…):返回datetime對象的時間部分:
?
| 1 2 3 4 5 | >>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>> a.time() datetime.time(16, 9, 33, 494248) |
3、utctimetuple(…):返回UTC時間元組:
?
| 1 2 3 4 5 | >>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>> a.utctimetuple() time.struct_time(tm_year=2017, tm_mon=3, tm_mday=22, tm_hour=16, tm_min=9, tm_sec=33, tm_wday=2, tm_yday=81, tm_isdst=0) |
4、combine(…):將一個date對象和一個time對象合并生成一個datetime對象:
?
| 1 2 3 4 5 | >>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) >>>datetime.datetime.combine(a.date(),a.time()) datetime.datetime(2017, 3, 22, 16, 9, 33, 494248) |
5、now(…):返回當前日期時間的datetime對象:
?
| 1 2 3 | >>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33, |
6、utcnow(…):返回當前日期時間的UTC datetime對象:
?
| 1 2 3 | >>> a = datetime.datetime.utcnow() >>> a datetime.datetime(2017, 3, 22, 8, 26, 54, 935242) |
7、strptime(…):根據string, format 2個參數,返回一個對應的datetime對象:
?
| 1 2 | >>> datetime.datetime.strptime('2017-3-22 15:25','%Y-%m-%d %H:%M') datetime.datetime(2017, 3, 22, 15, 25) |
8、utcfromtimestamp(…):UTC時間戳的datetime對象,時間戳值為time.time():
?
| 1 2 | >>> datetime.datetime.utcfromtimestamp(time.time()) datetime.datetime(2017, 3, 22, 8, 29, 7, 654272) |
五、timedelta類
timedelta類是用來計算二個datetime對象的差值的。
此類中包含如下屬性:
1、days:天數
2、microseconds:微秒數(>=0 并且 <1秒)
3、seconds:秒數(>=0 并且 <1天)
六、python日期計算實例
1.Python獲取當前日期時間:
?
| 1 2 3 4 5 6 7 8 9 10 | >>> now = datetime.datetime.now() >>> now datetime.datetime(2017, 3, 22, 16, 55, 49, 148233) >>> today = datetime.date.today() >>> today datetime.date(2017, 3, 22) >>> now.date() datetime.date(2017, 3, 22) >>> now.time() datetime.time(16, 55, 49, 148233) |
2.Python獲取上個月第一天和最后一天的日期:
?
| 1 2 3 4 5 6 7 8 9 | >>> today = datetime.date.today() >>> today datetime.date(2017, 3, 22) >>> mlast_day = datetime.date(today.year, today.month, 1) - datetime.timedelta(1) >>> mlast_day datetime.date(2017, 2, 28) >>> mfirst_day = datetime.date(mlast_day.year, mlast_day.month, 1) >>> mfirst_day datetime.date(2017, 2, 1) |
3.Python獲取時間差
時間差單位為秒
?
| 1 2 3 4 | >>> start_time = datetime.datetime.now() >>> end_time = datetime.datetime.now() >>> (end_time - start_time).seconds 7 |
差值不只是可以查看相差多少秒,還可以查看天(days), 秒(seconds), 微秒(microseconds).
4.Python計算當前時間向后8個小時的時間
?
| 1 2 3 4 | >>> d1 = datetime.datetime.now() >>> d2 = d1 + datetime.timedelta(hours = 8) >>> d2 datetime.datetime(2017, 3, 23, 1, 10, 37, 182240) |
可以計算: 天(days), 小時(hours), 分鐘(minutes), 秒(seconds), 微秒(microseconds).
5.Python計算上周一和周日的日期
?
| 1 2 3 4 5 6 7 8 9 10 | today = datetime.date.today() >>> today datetime.date(2017, 3, 23) >>> today_weekday = today.isoweekday() >>> last_sunday = today - datetime.timedelta(days=today_weekday) >>> last_monday = last_sunday - datetime.timedelta(days=6) >>> last_sunday datetime.date(2017, 3, 19) >>> last_monday datetime.date(2017, 3, 13) |
6.Python計算指定日期當月最后一天的日期和本月天數
?
| 1 2 3 4 5 6 7 8 9 10 11 12 | >>> date = datetime.date(2017,12,20) >>> def eomonth(date_object): ...? if date_object.month == 12: ...?? next_month_first_date = datetime.date(date_object.year+1,1,1) ...? else: ...?? next_month_first_date = datetime.date(date_object.year, date_object.month+1, 1) ...? return next_month_first_date - datetime.timedelta(1) ... >>> eomonth(date) datetime.date(2017, 12, 31) >>> eomonth(date).day 31 |
7.Python計算指定日期下個月當天的日期
這里要調用上一項中的函數eomonth(...)
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> date = datetime.date(2017,12,20)?????????? >>> def edate(date_object):????????????? ...? if date_object.month == 12:?????? ...?? next_month_date = datetime.date(date_object.year+1, 1,date_object.day) ...? else: ...?? next_month_first_day = datetime.date(date_object.year,date_object.month+1,1) ...?? if date_object.day > eomonth(last_month_first_day).day: ...??? next_month_date = datetime.date(date_object.year,date_object.month+1,eomonth(last_month_first_day).day) ...?? else: ...??? next_month_date = datetime.date(date_object.year, date_object.month+1, date_object.day) ...? return next_month_date ... >>> edate(date) datetime.date(2018, 1, 20) |
8.Python獲得本周一至今天的時間段并獲得上周對應同一時間段
?
| 1 2 3 4 5 6 7 8 9 10 11 12 | >>> today = datetime.date.today() >>> this_monday = today - datetime.timedelta(today.isoweekday()-1) >>> last_monday = this_monday - datetime.timedelta(7) >>> last_weekday = today -datetime.timedelta(7) >>> this_monday datetime.date(2017, 3, 20) >>> today datetime.date(2017, 3, 23) >>> last_monday datetime.date(2017, 3, 13) >>> last_weekday datetime.date(2017, 3, 16) |
附錄:python中時間日期格式化符號:
符號說明
| %y | 兩位數的年份表示(00-99) |
| %Y | 四位數的年份表示(000-9999) |
| %m | 月份(01-12) |
| %d | 月內中的一天(0-31) |
| %H | 24小時制小時數(0-23) |
| %I | 12小時制小時數(01-12) |
| %M | 分鐘數(00=59) |
| %S | 秒(00-59) |
| %a | 本地簡化星期名稱 |
| %A | 本地完整星期名稱 |
| %b | 本地簡化的月份名稱 |
| %B | 本地完整的月份名稱 |
| %c | 本地相應的日期表示和時間表示 |
| %j | 年內的一天(001-366) |
| %p | 本地A.M.或P.M.的等價符 |
| %U | 一年中的星期數(00-53)星期天為星期的開始 |
| %w | 星期(0-6),星期天為星期的開始 |
| %W | 一年中的星期數(00-53)星期一為星期的開始 |
| %x | 本地相應的日期表示 |
| %X | 本地相應的時間表示 |
| %Z | 當前時區的名稱 |
| %% | %號本身 |
轉載于:https://www.cnblogs.com/tortoise512/p/10773622.html
總結
以上是生活随笔為你收集整理的【转载】Python日期时间模块datetime详解与Python 日期时间的比较,计算实例代码的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。