python日期比较

import time
import datetime

'''
用第一个日期减去第二个日期(不带时分秒)
大于 返回1
等于 返回0
小于 返回-1
'''
def date_compare(date1, date2):
    try:
        time1 = time.mktime(time.strptime(date1, '%Y-%m-%d'))
        time2 = time.mktime(time.strptime(date2, '%Y-%m-%d'))
        #日期转化为int比较
        diff = int(time1)-int(time2)
        print(diff)
        if diff > 0:
            return 1
        elif diff == 0:
            return 0
        else:
            return -1
    except Exception as e:
        print(e)
        return ''
'''
第一个日期减去第二个日期
返回相差的天数
'''
def date_minus(date1, date2):
    try:
        time1 = time.mktime(time.strptime(date1, '%Y-%m-%d'))
        time2 = time.mktime(time.strptime(date2, '%Y-%m-%d'))
        #日期转化为int比较
        diff = int(time1)-int(time2)
        print(diff)
        return int(diff / 24 / 60 / 60)
    except Exception as e:
        print(e)
        return ''


#获取当前时间日期
nowTime_str = datetime.datetime.now().strftime('%Y-%m-%d')
print(nowTime_str)
#mktime参数为struc_time,将日期转化为秒,
datediff = date_compare(nowTime_str, '2020-04-02')
print('datediff==>', datediff)

datediff = date_minus('2020-04-05', '2020-04-02')
print('datediff==>', datediff)

输出:

datediff==> -1
datediff==> 3

你可能感兴趣的:(Python,python)