CPak
CPak

Reputation: 13581

Calculate days to the next holiday day

I want to calculate the number of days to the next holiday (e.g., Christmas). For instance, if the input is 2019-12-01 then the answer would be 24 days as shown below:

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

I want a solution that does not require specifying the year in the holiday date. For instance, if the input is 2018-12-01 or 2016-12-01, I should not have to manually define xmas2018 or xmas2016 and calculate the difference in days. Assume that input_date is a proper datetime variable

def days_to_xmas(input_date):
    ...
    ans = (input_date - ...).days
    return ans

Upvotes: 0

Views: 1448

Answers (1)

lmiguelvargasf
lmiguelvargasf

Reputation: 69725

You should use auxiliary function to compute Christmas based upon your input. Based on the feedback provided by @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

Then use the function you are defining:

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

The following function is simplified assuming that input_date is a datetime variable

def days_to_xmas(input_date):
    ans = (get_christmas(input_date) - input_date).days
    return ans

Some examples to validate

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

Upvotes: 1

Related Questions