LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates

简介: LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates

LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates


Table of Contents

中文版:

英文版:

My  answer:

中文版:

请你编写一个程序来计算两个日期之间隔了多少天。

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

 

英文版:

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.

My  answer:

import time
class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        time1 = time.mktime(time.strptime(date1,'%Y-%m-%d'))
        time2 = time.mktime(time.strptime(date2,'%Y-%m-%d'))
        result = abs(int((time2 - time1)/(24*60*60)))
        return result

看到题解的另一种方法:

from datetime import datetime 
class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        date1 = datetime.strptime(date1,'%Y-%m-%d')
        date2 = datetime.strptime(date2,'%Y-%m-%d')
        res = abs((date1 - date2).days)
        return res
作者:z1m
链接:https://leetcode-cn.com/problems/number-of-days-between-two-dates/solution/pythonshi-yong-ku-by-z1m/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关文章
|
5月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
64 1
|
3月前
|
SQL
leetcode-SQL-1164. 指定日期的产品价格
leetcode-SQL-1164. 指定日期的产品价格
18 0
|
5月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
21 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5475. 统计好三元组 Count Good Triplets
LeetCode contest 200 5475. 统计好三元组 Count Good Triplets
LeetCode contest 199 灯泡开关 IV Bulb Switcher IV
LeetCode contest 199 灯泡开关 IV Bulb Switcher IV
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
|
机器学习/深度学习
LeetCode contest 190 5416. 检查单词是否为句中其他单词的前缀
LeetCode contest 190 5416. 检查单词是否为句中其他单词的前缀
|
算法 C#
LeetCode contest 189 5413. 重新排列句子中的单词
LeetCode contest 189 5413. 重新排列句子中的单词

热门文章

最新文章