两个日期(datetime)之间的差异

4

我正在尝试用Python编写一个计算两个日期之间天数的程序。

我从用户处以"May 2 2020"的格式获取输入。我学习到应该首先将字符串解析为日期,但我不知道该如何实现。请帮我。

以下是我尝试过的程序:

from datetime import date

first_date(input)
sec_date(input)
con_date = datetime.strptime(first_date, '%d %m %Y').date()
con_date2 = datetime.strptime(first_date, '%d %m %Y').date()
delta = con_date2 - con_date
print(delta)

如果我以字符串形式输入May 2 2020作为first_date,以Jun 30 2020作为sec_date,我该如何将此字符串转换为日期格式?注意:输入应按上述格式给出。

以上代码无法将字符串转换为日期。请帮助我将其转换为日期,并找出从sec_date到first_date的天数。

4个回答

3

您可以使用适当的strptime 格式简单解析时间。

然后,一旦您获得了两个date对象,您可以简单地对它们进行减法操作:

import datetime 

d1_str = "Apr 29 2020"
d2_str = "May 7 2020"

fmt = "%b %d %Y"

d1 = datetime.datetime.strptime(d1_str, fmt).date()
d2 = datetime.datetime.strptime(d2_str, fmt).date()

delta = d2 - d1
print(delta)
print(delta.days)

输出结果为:

6 days, 0:00:00
6

@NicolasM应该怎么做才能接受YYYY和YY格式的年份。比如2019和19。 - Ashok Kumar

2
from datetime import datetime

first_date = "May 2 2020"
sec_date = "Jun 30 2020"
con_date = datetime.strptime(first_date, '%b %d %Y').date()
con_date2 = datetime.strptime(sec_date, '%b %d %Y').date()
delta = con_date2 - con_date
print(delta.days)

太好了。谢谢。 - Ashok Kumar
应该如何接受YYYY和YY格式的年份。例如2019和19。 - Ashok Kumar
@AshokKumar,请将大写的%Y替换为小写的%y。 - 305Curtis
我不确定这个程序是否能够接受两种格式,但这是你在两种格式之间切换的方法。如果可能的话,你应该让所有用户输入都采用相同的格式。或者你可以检查年份的格式是 YYYY 还是 YY,然后相应地处理输入。 - 305Curtis
@AshokKumar,你搞清楚如何接受两种年份格式了吗? - 305Curtis
是的,我修改了下面用户Tabulate的代码,添加了另外一些try和validate块来检查%Y和%y。现在它可以正常工作,但代码变得冗长了。 - Ashok Kumar

1
这应该会有所帮助。
import datetime

str = "May 2 2020"
str2 = "June 30 2020"
#convert str of month to int
str = str.split(" ")
str2 = str2.split(" ")
month_name = str[0]
month_name2 = str2[0]

try:
    datetime_object = datetime.datetime.strptime(month_name, "%B")
except ValueError:
    datetime_object = datetime.datetime.strptime(month_name, "%b")
month_number = datetime_object.month

try:
    datetime_object = datetime.datetime.strptime(month_name2, "%B")
except ValueError:
    datetime_object = datetime.datetime.strptime(month_name2, "%b")
month_number2 = datetime_object.month

#find number of days between dates

d0 = datetime.date(int(str[2]), month_number, int(str[1]))
d1 = datetime.date(int(str2[2]), month_number2, int(str2[1]))
delta = d1 - d0
print(delta.days)

非常适合像我这样的新手逐步学习的优秀程序。谢谢。 - Ashok Kumar

1

这是一种可以应用的方法,它需要两个参数:起始日期和结束日期,并返回它们之间的天数差异。

希望对您有所帮助。
from datetime import date
import time

first_date = input("Enter First Date: ").split(" ")
sec_date = input("Enter Second Date: ").split(" ")

def getTimeDiff(fist_date, second_date):
    month1 = time.strptime(first_date[0], "%b").tm_mon
    month2 = time.strptime(second_date[0], "%b").tm_mon

    date1 = date(int(fist_date[2]), month1, int(first_date[1]))
    date2 = date(int(second_date[2]), month2, int(second_date[1]))
    delta = date2 - date1
    return delta.days

res = getTimeDiff(first_date, sec_date)
print(res)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接