日期模块之间的比较
python中的datetime模块提供了操作日期和时间功能,该模块提供了五种核心对象:datetime时间日期类型,date日期类型,time时间类型,tzinfo时区类型,timedelta时间差类型,今天为大家介绍一下datetime模块的具体使用方法与python日期时间计算与比较的相关实例.
一、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
日期三部分构成:
date(year,month,day)
2、 通过year
, month
, day
三个数据描述符可以进行访问:
>>> a = datetime.date.today() >>> a datetime.date(2017, 3, 22) >>> a.year 2017 >>> a.month 3 >>> a.day 22
3、用__getattribute__(...)
方法获得上述值:
>>> 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<y) | x.__lt__(y) |
__ne__(…) | 不等于(x!=y) | x.__ne__(y) |
以上方法的返回值为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) True a = "2020-01-01" b = "2020-01-05" if a.__lt__(b) == True: print(11111111) else: print(222222222222) ##### 11111111
2、获得二个日期相差多少天
使用__sub__(...)
和__rsub__(...)
方法,其实二个方法差不太多,一个是正向操作,一个是反向操作:
方法名 | 方法说明 | 用法 |
__sub__(…) | x - y | x.__sub__(y) |
__rsub__(…) | y - x | x.__rsub__(y) |
示例 :
import datetime a = "2020-01-01" b = "2020-01-05" a = datetime.datetime.strptime(a, '%Y-%m-%d') b = datetime.datetime.strptime(b, '%Y-%m-%d') a = datetime.datetime.date(a) b = datetime.datetime.date(b) # 计算结果的返回值类型为 datetime.timedelta , 如果获得整数类型的结果则 .days ret = a.__sub__(b) print(ret.days) # -4 res = a.__rsub__(b) print(res.days) # 4 # 注意 : 里面的类型可以是 datetime.datetime 和 datetime.date 类型, 不能是str类型
3、ISO标准化日期
如果想要让所使用的日期符合ISO标准,那么使用如下三个方法:
1).* isocalendar(...)
*:返回一个包含三个值的元组,三个值依次为:year
年份,week number
周数,weekday
星期数(周一为1…周日为7):
import datetime a = "2020-01-01" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.isocalendar() print(c) # (2020, 1, 3) print(c[0]) # 2020 年份 print(c[1]) # 1 周数 print(c[2]) # 3 星期
2). isoformat(...)
: 返回符合ISO 8601标准 (YYYY-MM-DD
) 的日期字符串;
>>> a = datetime.date(2017,3,22) >>> a.isoformat() '2017-03-22'
3). isoweekday(...)
: 返回符合ISO标准的指定日期所在的星期数(周一为1…周日为7)
import datetime a = "2020-01-01" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.isoweekday() print(c) # 3
4).与isoweekday(...)
相似的还有一个weekday(...)
方法,只不过是weekday(...)
方法返回的周一为 0, 周日为 6
import datetime a = "2020-01-01" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.weekday() print(c) # 2 ## 对应关系 week_day_dict = { 0: "星期一", 1: "星期二", 2: "星期三", 3: "星期四", 4: "星期五", 5: "星期六", 6: "星期日" }
4、其他方法与属性
1). timetuple(...)
:该方法为了兼容time.localtime(...)
返回一个类型为time.struct_time
的数组,但有关时间的部分元素值为0:
import datetime a = "2020-01-01" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.timetuple() print(c) # time.struct_time(tm_year=2020, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=1, tm_isdst=-1) print(c.tm_year) # 2020 print(c.tm_mon) # 1 print(c.tm_mday) # 1
2).toordinal(...)
: 返回公元公历开始到现在的天数。公元1年1月1日为1
import datetime a = "2020-01-01" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.toordinal() print(c) # 737425
3). replace(...)
:返回一个替换指定日期字段的新date对象。参数3个可选参数,分别为year,month,day。注意替换是产生新对象,不影响原date对象。
import datetime a = "2020-01-01" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.replace(2020, 3, 17) print(c) # 2020-03-17
4).resolution
:date对象表示日期的最小单位。这里是天。
import datetime a = "2020-01-19" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.resolution print(c.days) # 1
5).fromordinal(...)
:将Gregorian日历时间转换为date对象;Gregorian Calendar :一种日历表示方法,类似于我国的农历,西方国家使用比较多。
import datetime a = "2020-01-19" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) b = a.toordinal() c = datetime.date.fromordinal(b) print(c) # 2020-01-19
6).fromtimestamp(...)
:根据给定的时间戮,返回一个date对象
import time print(time.time()) # 1585641241.6905062 a = datetime.date.fromtimestamp(time.time()) print(a) # 2020-03-31
7).today(...)
:返回当前日期
import datetime a = datetime.date.today() print(a) # 2020-03-31
8).max
: date类能表示的最大的年、月、日的数值
import datetime a = datetime.date.max print(a) # 9999-12-31
9).min
: date类能表示的最小的年、月、日的数值
import datetime a = datetime.date.min print(a) # 0001-01-01
(三)、日期的字符串输出
1、如果你想将日期对象转化为字符串对象的话,可以用到__format__(...)
方法以指定格式进行日期输出:
import datetime a = "2020-01-19" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.__format__('%Y-%m-%d') c2 = a.__format__('%Y/%m/%d') c3 = a.__format__('%Y-%m-%d') c4 = a.__format__('%D') print(c) # 2020-01-19 print(c2) # 2020/01/19 print(c3) # 2020-01-19 print(c4) # 01/19/20
与此方法等价的方法为strftime(...)
import datetime a = "2020-01-19" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.strftime("%Y%m%d") print(c) # 20200119
2、如果只是相简单的获得日期的字符串,则使用__str__(...)
import datetime a = "2020-01-19" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.__str__() print(c) # '2020-01-19'
3、如果想要获得ctime样式的格式请使用ctime(...)
:
import datetime a = "2020-01-19" a = datetime.datetime.strptime(a, '%Y-%m-%d') a = datetime.datetime.date(a) c = a.ctime() print(c) # Sun Jan 19 00:00:00 2020
三、time类
(一)、time类的数据构成
time
类由hour
小时、minute
分钟、second
秒、microsecond
毫秒和tzinfo
五部分组成
time([hour[, minute[, second[, microsecond[, tzinfo]]]]])
相应的,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.tzinfo
与date
类一样,time
类也包含__getattribute__(...)
方法可以读取相关属性:
>>> a.__getattribute__('hour') 12 >>> a.__getattribute__('minute') 20 >>> a.__getattribute__('second') 59
(二)、time类中的方法和属性
1、python比较时间大小
相关方法包括:__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) False
2、__nonzero__(...)
判断时间对象是否非零,返回值为True/False:
>>> a = datetime.time(12,20,59,899) >>> a.__nonzero__() True
3、其他属性
1)、max
:最大的时间表示数值:
>>> datetime.time.max
datetime.time(23, 59, 59, 999999)
2)、min
:最小的时间表示数值
>>> datetime.time.min
datetime.time(0, 0)
3)、resolution
:时间间隔单位为分钟
>>> datetime.time.resolution
datetime.timedelta(0, 0, 1)
(三)、时间的字符串输出
1、如果你想将时间对象转化为字符串对象的话,可以用到__format__(...)
方法以指定格式进行时间输出:
>>> a = datetime.time(12,20,59,899) >>> a.__format__('%H:%M:%S') '12:20:59'
与此方法等价的方法为strftime(...)
>>> a = datetime.time(12,20,59,899) >>> a.strftime('%H:%M:%S') '12:20:59'
关于格式化字符串的相关内容,请查阅本文最后的:附录:python中时间日期格式化符号
2、ISO标准输出
如果要使输出的时间字符符合ISO标准,请使用isoformat(...)
:
>>> a = datetime.time(12,20,59,899) >>> a.isoformat() '12:20:59.000899'
3、如果只是相简单的获得时间的字符串,则使用__str__(...)
>>> a = datetime.time(12,20,59,899) >>> a.__str__() '12:20:59.000899'
四、datetime类
(一)、datetime类的数据构成
datetime
类其实是可以看做是date
类和time
类的合体,其大部分的方法和属性都继承于这二个类
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
(二)、专属于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)
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)
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)
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)
5、now(…):返回当前日期时间的datetime对象:
>>> a = datetime.datetime.now() >>> a datetime.datetime(2017, 3, 22, 16, 9, 33,
6、utcnow(…):返回当前日期时间的UTC datetime对象:
>>> a = datetime.datetime.utcnow() >>> a datetime.datetime(2017, 3, 22, 8, 26, 54, 935242)
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)
8、utcfromtimestamp(…):UTC时间戳的datetime对象,时间戳值为time.time():
>>> 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天)
原文链接 : https://www.jb51.net/article/147429.htm