leetcode 1360. Number of Days Between Two Dates(python)

描述

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

Note:

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

解析

根据题意,就是计算两个日期中间隔了多少天,我直接使用了 python 语法,比较简单,大家不要学我,可以通过手动的计算方法来计算更有水平。

解答

class Solution(object):
    def daysBetweenDates(self, date1, date2):
        """
        :type date1: str
        :type date2: str
        :rtype: int
        """
        d1 = date1.split("-")
        d2 = date2.split("-")
        d1 = datetime.datetime(int(d1[0].lstrip("0")), int(d1[1].lstrip("0")), int(d1[2].lstrip("0")))
        d2 = datetime.datetime(int(d2[0].lstrip("0")), int(d2[1].lstrip("0")), int(d2[2].lstrip("0")))
        r = abs(d1 - d2)
        return r.days

运行结果

Runtime: 20 ms, faster than 51.95% of Python online submissions for Number of Days Between Two Dates.
Memory Usage: 13.5 MB, less than 83.12% of Python online submissions for Number of Days Between Two Dates.

原题链接:https://leetcode.com/problems/number-of-days-between-two-dates/

您的支持是我最大的动力

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