1360. 日期之间隔几天
请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。
示例 1:
输入:date1 = "2019-06-29", date2 = "2019-06-30"
输出:1
示例 2:
输入:date1 = "2020-01-15", date2 = "2019-12-31"
输出:15
提示:
给定的日期是 1971 年到 2100 年之间的有效日期。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-days-between-two-dates
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: return abs(datetime.datetime.strptime(date1,'%Y-%m-%d')-datetime.datetime.strptime(date2,'%Y-%m-%d')).days
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: import datetime date1 = map(int, date1.split("-")) date2 = map(int, date2.split("-")) date1 = datetime.date(*date1) date2 = datetime.date(*date2) return abs((date1-date2).days)
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: month_run = [31,29,31,30,31,30,31,31,30,31,30,31] month_normal = [31,28,31,30,31,30,31,31,30,31,30,31] if date1 > date2: date1, date2 = date2, date1 def simplify_number(number_string): if number_string[0] == 0: number = int(number_string[1:]) else: number = int(number_string) return number def if_run_nian(year): return year % 100 != 0 and year % 4 == 0 or year % 400 ==0 year1 = simplify_number(date1[0:4]) year2 = simplify_number(date2[0:4]) day1 = simplify_number(date1[8:]) day2 = simplify_number(date2[8:]) month1 = simplify_number(date1[5:7]) month2 = simplify_number(date2[5:7]) delta_year = year2 - year1 delta_month = abs(month2 - month1) day = 0 if delta_year >= 2: for i in range(1,delta_year): if if_run_nian(year1+i): day += 366 else: day += 365 if if_run_nian(year1): month_list1 = month_run else: month_list1 = month_normal if if_run_nian(year2): month_list2 = month_run else: month_list2 = month_normal if delta_year >= 1: for i in range(month1, 12): day += month_list1[i] for k in range(0,month2-1): day += month_list2[k] day = day + (month_list1[month1-1] - day1) + day2 else: if delta_month == 0: day = day + day2 - day1 elif delta_month == 1: day = day + (month_list1[month1-1] - day1) + day2 else: day = day + (month_list1[month1-1] - day1) + day2 for i in range(month1,month2-1): day += month_list1[i] return day
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def if_run_nian(year): return year % 100 != 0 and year % 4 == 0 or year % 400 ==0 def cnt_day(date): y, m, total = map(int, date.split("-")) for i in range(1971, y): total += 366 if if_run_nian(i) else 365 for i in range(m): total += months[i] if m > 2 and if_run_nian(y): total += 1 return total return abs(cnt_day(date2) - cnt_day(date1))