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

问题描述 投票:3回答:4

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

我正在以2020年5月2日的格式从用户那里得到输入。我了解到我应该首先将字符串解析为日期,但是我不知道该怎么做。请帮助我。

这是我尝试过的程序:

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)

如果我以first_date的字符串May 2 2020和sec_date的字符串Jun 30 2020的形式输入,如何将该字符串转换为日期格式?注意:只能以上述格式输入。

上面的代码不适用于我将字符串转换为日期。请帮助我将其转换为日期,并找出sec_date到first_date之间的天数。

python date difference python-datetime
4个回答
3
投票

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

然后,获得两个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

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)

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)

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)
© www.soinside.com 2019 - 2024. All rights reserved.