?
作者:cmzsteven
出處:https://blog.csdn.net/cmzsteven/article/details/64906245
?
一、datetime模塊介紹
(一)、datetime模塊中包含如下類:
(二)、datetime模塊中包含的常量
?
二、date類
(一)、date對象構成
1、date對象由year年份、month月份及day日期三部分構成:
date(year,month,day)1
2、 通過year, month, day三個數據描述符可以進行訪問:
>>> a = datetime.date.today()
>>> a
datetime.date(2017, 3, 22)
>>> a.year
2017
>>> a.month
3
>>> a.day
22 123456789
3、當然,你也可以用__getattribute__(...)方法獲得上述值:
>>> a.__getattribute__('year')
2017
>>> a.__getattribute__('month')
3
>>> a.__getattribute__('day')
22123456
?
(二)、date對象中包含的方法與屬性
1、用于日期比較大小的方法
以上方法的返回值為True\False
示例如下:
>>> 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)
True1234567891011121314
?
2、獲得二個日期相差多少天
使用__sub__(...)和__rsub__(...)方法,其實二個方法差不太多,一個是正向操作,一個是反向操作:
示例如下:
>>> a
datetime.date(2017, 3, 22)
>>> b
datetime.date(2017, 3, 15)
>>> a.__sub__(b)
datetime.timedelta(7)
>>> a.__rsub__(b)
datetime.timedelta(-7)12345678
計算結果的返回值類型為datetime.timedelta, 如果獲得整數類型的結果則按下面的方法操作:
>>> a.__sub__(b).days
7
>>> a.__rsub__(b).days
-71234
?
3、ISO標準化日期
如果想要讓所使用的日期符合ISO標準,那么使用如下三個方法:
1).* isocalendar(...)*:返回一個包含三個值的元組,三個值依次為:year年份,week number周數,weekday星期數(周一為1…周日為7):
示例如下:
>>> a = datetime.date(2017,3,22)
>>> a.isocalendar()
(2017, 12, 3)
>>> a.isocalendar()[0]
2017
>>> a.isocalendar()[1]
12
>>> a.isocalendar()[2]
3123456789
2). isoformat(...): 返回符合ISO 8601標準 (YYYY-MM-DD) 的日期字符串;
示例如下
>>> a = datetime.date(2017,3,22)
>>> a.isoformat()
'2017-03-22'123
3). isoweekday(...): 返回符合ISO標準的指定日期所在的星期數(周一為1…周日為7)
示例如下:
>>> a = datetime.date(2017,3,22)
>>> a.isoweekday()
3123
4).與isoweekday(...)相似的還有一個weekday(...)方法,只不過是weekday(...)方法返回的周一為 0, 周日為 6
示例如下:
>>> a = datetime.date(2017,3,22)
>>> a.weekday()
2123
?
4、其他方法與屬性
1). timetuple(...):該方法為了兼容time.localtime(...)返回一個類型為time.struct_time的數組,但有關時間的部分元素值為0:
>>> 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
22123456789
2).toordinal(...): 返回公元公歷開始到現在的天數。公元1年1月1日為1
>>> a = datetime.date(2017,3,22)
>>> a.toordinal()
736410123
3). replace(...):返回一個替換指定日期字段的新date對象。參數3個可選參數,分別為year,month,day。注意替換是產生新對象,不影響原date對象。
>>> a = datetime.date(2017,3,22)
>>> b = a.replace(2017,2,28)
>>> a
datetime.date(2017, 3, 22)
>>> b
datetime.date(2017, 2, 28)123456
4).resolution:date對象表示日期的最小單位。這里是天。
>>> datetime.date.resolution
datetime.timedelta(1)12
5).fromordinal(...):將Gregorian日歷時間轉換為date對象;Gregorian Calendar :一種日歷表示方法,類似于我國的農歷,西方國家使用比較多。
>>> a = datetime.date(2017,3,22)
>>> b = a.toordinal()
>>> datetime.date.fromordinal(b)
datetime.date(2017, 3, 22)1234
6).fromtimestamp(...):根據給定的時間戮,返回一個date對象
>>> time.time()
1490165087.2242179
>>> datetime.date.fromtimestamp(time.time())
datetime.date(2017, 3, 22)1234
7).today(...):返回當前日期
>>> datetime.date.today()
datetime.date(2017, 3, 22)12
8).max: date類能表示的最大的年、月、日的數值
>>> datetime.date.max
datetime.date(9999, 12, 31)12
9).min: date類能表示的最小的年、月、日的數值
>>> datetime.date.min
datetime.date(1, 1, 1)12
?
(三)、日期的字符串輸出
1、如果你想將日期對象轉化為字符串對象的話,可以用到__format__(...)方法以指定格式進行日期輸出:
>>> 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'123456789
與此方法等價的方法為strftime(...)
>>> a.strftime("%Y%m%d")
'20170322'12
關于格式化字符串的相關內容,請查閱本文最后的:附錄:python中時間日期格式化符號
2、如果只是相簡單的獲得日期的字符串,則使用__str__(...)
>>> a.__str__()
'2017-03-22'12
3、如果想要獲得ctime樣式的格式請使用ctime(...):
>>> a.ctime()
'Wed Mar 22 00:00:00 2017'
123
?
三、time類
(一)、time類的數據構成
time類由hour小時、minute分鐘、second秒、microsecond毫秒和tzinfo五部分組成
time([hour[, minute[, second[, microsecond[, tzinfo]]]]])1
相應的,time類中就有上述五個變量來存儲應該的值:
>>> 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.tzinfo123456789101112
與date類一樣,time類也包含__getattribute__(...)方法可以讀取相關屬性:
>>> a.__getattribute__('hour')
12
>>> a.__getattribute__('minute')
20
>>> a.__getattribute__('second')
59123456
?
(二)、time類中的方法和屬性
1、比較時間大小
相關方法包括:__eq__(...), __ge__(...), __gt__(...), __le__(...), __lt__(...), __ne__(...)
這里的方法與date類中定義的方法大同小異,使用方法與一樣,這里就不過多介紹了,示例如下:
>>> 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)
False1234567891011121314
?
2、__nonzero__(...)
判斷時間對象是否非零,返回值為True/False:
>>> a = datetime.time(12,20,59,899)
>>> a.__nonzero__()
True123
?
3、其他屬性
1)、max:最大的時間表示數值:
>>> datetime.time.max
datetime.time(23, 59, 59, 999999)12
2)、min:最小的時間表示數值
>>> datetime.time.min
datetime.time(0, 0)12
3)、resolution:時間間隔單位為分鐘
>>> datetime.time.resolution
datetime.timedelta(0, 0, 1)12
?
(三)、時間的字符串輸出
1、如果你想將時間對象轉化為字符串對象的話,可以用到__format__(...)方法以指定格式進行時間輸出:
>>> a = datetime.time(12,20,59,899)
>>> a.__format__('%H:%M:%S')
'12:20:59'123
與此方法等價的方法為strftime(...)
>>> a = datetime.time(12,20,59,899)
>>> a.strftime('%H:%M:%S')
'12:20:59'123
關于格式化字符串的相關內容,請查閱本文最后的:附錄:python中時間日期格式化符號
2、ISO標準輸出
如果要使輸出的時間字符符合ISO標準,請使用isoformat(...):
>>> a = datetime.time(12,20,59,899)
>>> a.isoformat()
'12:20:59.000899'123
3、如果只是相簡單的獲得時間的字符串,則使用__str__(...)
>>> a = datetime.time(12,20,59,899)
>>> a.__str__()
'12:20:59.000899'123
?
四、datetime類
(一)、datetime類的數據構成
datetime類其實是可以看做是date類和time類的合體,其大部分的方法和屬性都繼承于這二個類,相關的操作方法請參閱,本文上面關于二個類的介紹。其數據構成也是由這二個類所有的屬性所組成的。
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])1
?
(二)、專屬于datetime的方法和屬性
1、 date(…):返回datetime對象的日期部分:
>>> a = datetime.datetime.now()
>>> a
datetime.datetime(2017, 3, 22, 16, 9, 33, 494248)
>>> a.date()
datetime.date(2017, 3, 22)12345
?
2、time(…):返回datetime對象的時間部分:
>>> a = datetime.datetime.now()
>>> a
datetime.datetime(2017, 3, 22, 16, 9, 33, 494248)
>>> a.time()
datetime.time(16, 9, 33, 494248)12345
?
3、utctimetuple(…):返回UTC時間元組:
>>> 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)12345
?
4、combine(…):將一個date對象和一個time對象合并生成一個datetime對象:
>>> 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)12345
?
5、now(…):返回當前日期時間的datetime對象:
>>> a = datetime.datetime.now()
>>> a
datetime.datetime(2017, 3, 22, 16, 9, 33, 123
?
6、utcnow(…):返回當前日期時間的UTC datetime對象:
>>> a = datetime.datetime.utcnow()
>>> a
datetime.datetime(2017, 3, 22, 8, 26, 54, 935242)123
?
7、strptime(…):根據string, format 2個參數,返回一個對應的datetime對象:
>>> datetime.datetime.strptime('2017-3-22 15:25','%Y-%m-%d %H:%M')
datetime.datetime(2017, 3, 22, 15, 25)12
?
8、utcfromtimestamp(…):UTC時間戳的datetime對象,時間戳值為time.time():
>>> datetime.datetime.utcfromtimestamp(time.time())
datetime.datetime(2017, 3, 22, 8, 29, 7, 654272)12
?
五、timedelta類
timedelta類是用來計算二個datetime對象的差值的。
此類中包含如下屬性:
1、days:天數
2、microseconds:微秒數(>=0 并且 <1秒)
3、seconds:秒數(>=0 并且 <1天)
?
六、日期計算實操
1.獲取當前日期時間:
>>> 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)12345678910
?
2.獲取上個月第一天和最后一天的日期:?
>>> 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)123456789
?
3.獲取時間差
時間差單位為秒
>>> start_time = datetime.datetime.now()
>>> end_time = datetime.datetime.now()
>>> (end_time - start_time).seconds
71234
差值不只是可以查看相差多少秒,還可以查看天(days), 秒(seconds), 微秒(microseconds).
?
4.計算當前時間向后8個小時的時間
>>> d1 = datetime.datetime.now()
>>> d2 = d1 + datetime.timedelta(hours = 8)
>>> d2
datetime.datetime(2017, 3, 23, 1, 10, 37, 182240)1234
可以計算: 天(days), 小時(hours), 分鐘(minutes), 秒(seconds), 微秒(microseconds).
?
5.計算上周一和周日的日期
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)12345678910
?
6.計算指定日期當月最后一天的日期和本月天數
>>> 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
31123456789101112
?
7.計算指定日期下個月當天的日期
這里要調用上一項中的函數eomonth(...)
>>> 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)1234567891011121314
?
8.獲得本周一至今天的時間段并獲得上周對應同一時間段
>>> 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)123456789101112
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
