Python实现时间比较

用到的库:datetime.datetime.now()    datetime.datetime.strptime()    datetime.timedelta()
数据模拟:
>>> from datetime import datetime, timedelta
>>> nowtime = datetime.now()    # 现在的时间
>>> nowtime
datetime.datetime(2017, 6, 20, 20, 11, 12, 926763)
>>> 
>>> lasthour = datetime(2017, 6, 20, 19, 11, 12, 926763)    # 1个小时前的时间
>>> lasthour
datetime.datetime(2017, 6, 20, 19, 11, 12, 926763)
>>> lasthour_str = str(lasthour)          # 模拟从数据库取出来的str类型时间数据
>>> lasthour_str
'2017-06-20 19:11:12.926763'

str时间数据转换:
# 将str类型时间数据转换为datetime.datetime类型时间数据
>>> lasthour_new = datetime.strptime(lasthour_str, '%Y-%m-%d %H:%M:%S.%f')
>>> lasthour_new
datetime.datetime(2017, 6, 20, 19, 11, 12, 926763)

时间比较:
# lasthour_new和nowtime的时间差是否大于1个小时
>>> nowtime - lasthour_new > timedelta(hours=1)
False
# lasthour_new和nowtime的时间差是否等于1个小时
>>> nowtime - lasthour_new == timedelta(hours=1)
True
# lasthour_new和nowtime的时间差是否大于60分钟
>>> nowtime - lasthour_new > timedelta(minutes=60)
False
# lasthour_new和nowtime的时间差是否等于60分钟
>>> nowtime - lasthour_new == timedelta(minutes=60)
True

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/57f8d442b873c33c42537ad282ad7717.html