我想计算到下一个假期(例如圣诞节(的天数。例如,如果输入2019-12-01
则答案将24 days
如下所示:
import datetime
START_DATE = '2019-12-01'
startdate = datetime.datetime.strptime(START_DATE, '%Y-%m-%d')
XMAS_2019 = '2019-12-25'
xmas2019 = datetime.datetime.strptime(XMAS_2019, '%Y-%m-%d')
(xmas2019-startdate).days
# 24
我想要一个不需要在假期日期指定年份的解决方案。例如,如果输入是2018-12-01
或2016-12-01
,我不应该手动定义xmas2018
或xmas2016
并计算天数的差异。假设input_date
是适当的datetime
变量
def days_to_xmas(input_date):
...
ans = (input_date - ...).days
return ans
您应该使用辅助函数根据您的输入计算圣诞节。根据@MarkRansom提供的反馈:
import datetime
def get_christmas(date):
"""Returns the date of the Christmas of the year of the date"""
next_xmas = datetime.datetime(date.year, 12, 25)
if next_xmas < date:
next_xmas = datetime.datetime(date.year+1, 12, 25)
return next_xmas
然后使用您定义的函数:
def days_to_xmas(input_date):
if type(input_date) is str:
startdate = datetime.datetime.strptime(input_date, '%Y-%m-%d')
else:
startdate = input_date
ans = (get_christmas(startdate) - startdate).days
return ans
假设input_date
是datetime
变量,则简化了以下函数
def days_to_xmas(input_date):
ans = (get_christmas(input_date) - input_date).days
return ans
一些要验证的示例
days_to_xmas(datetime.datetime.strptime('2017-12-01', '%Y-%m-%d'))
# 24
days_to_xmas(datetime.datetime.strptime('2017-12-26', '%Y-%m-%d'))
# 364