LeetCode | 1360. Number of Days Between Two Dates日期之間隔幾天【Python】

LeetCode 1360. Number of Days Between Two Dates日期之間隔幾天【Easy】【Python】【數學】

Problem

LeetCode

Write a program to count the number of days between two dates.

The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

Example 1:

Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1

Example 2:

Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15

Constraints:

  • The given dates are valid dates between the years 1971 and 2100.

問題

力扣

請你編寫一個程序來計算兩個日期之間隔了多少天。

日期以字符串形式給出,格式爲 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 年之間的有效日期。

思路

數學

解法一:

調用 datetime 庫。

解法二:

手動計算日期天數。

Python3代碼

解法一:

class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        # solution one: datetime
        import datetime
        year1, month1, day1 = date1[0:4], date1[5:7], date1[8:10]
        year2, month2, day2 = date2[0:4], date2[5:7], date2[8:10]
        d1 = datetime.datetime(int(year1), int(month1) , int(day1))   # date1
        d2 = datetime.datetime(int(year2), int(month2) , int(day2))   # date2
        return abs((d1 - d2).days)

解法二:

class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        # solution two: manual calculation
        y1, m1, d1 = map(int, date1.split('-'))
        y2, m2, d2 = map(int, date2.split('-'))
        months = [0,31,28,31,30,31,30,31,31,30,31,30,31]
        
        # get days from 1971
        def getDays(y, m, d):
            ans = 0
            # calculate years
            for i in range(1971, y):
                if (i % 4 == 0 and i % 100 != 0) or i % 400 == 0:  # leap year
                    ans += 366
                else:
                    ans += 365
            # calculate months
            for i in range(1, m):
                if i == 2:  # February
                    ans += 29 if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0 else 28
                else:
                    ans += months[i]
            return ans + d  # calculate days
        
        days1 = getDays(y1, m1, d1)
        days2 = getDays(y2, m2, d2)
        return abs(days1 - days2)

代碼地址

GitHub鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章