【Python】计算两个日期/时间相差多少天/天数
def calcDateDiff(startDate: str, endDate: str, dateFormat='%Y/%m/%d'): """ 计算两个日期相差多少天 :param startDate: 开始日期 eg: '2020/03/25' :param endDate: 结束日期 eg: '2020/03/30' :param dateFormat: startDate和endDate 的 日期格式 默认 '%Y/%m/%d' :return: 相差天数 eg:5 """ # 1、日期转换为 %Y%m%d 格式 startDate = time.strftime('%Y%m%d', time.localtime(time.mktime(time.strptime(startDate, dateFormat)))) endDate = time.strftime('%Y%m%d', time.localtime(time.mktime(time.strptime(endDate, dateFormat)))) # 2、开始计算相差天数 start = startDate end = endDate old = datetime.datetime(int(start[0:4]), int(start[4:6]), int(start[6:8])) now = datetime.datetime(int(end[0:4]), int(end[4:6]), int(end[6:8])) count = (now - old).days return count if __name__ == '__main__': # 2020/03/25-2020/03/30 相差5天 print(f"2020/03/25-2020/03/30 相差{calcDateDiff('2020/03/25', '2020/03/30')}天") # 20200101-20200110 相差9天 print(f"20200101-20200110 相差{calcDateDiff('20200101', '20200110','%Y%m%d')}天") # 2020-02-12-2020-02-10 相差-2天 print(f"2020-02-12-2020-02-10 相差{calcDateDiff('2020-02-12', '2020-02-10','%Y-%m-%d')}天")
如果忍耐算是坚强 我选择抵抗 如果妥协算是努力 我选择争取