forvas
forvas

Reputation: 10179

How to get the next specific day of the month in Python?

I am using Python 2.7.

I want to get the next 25th day of the month from now on. Today is February 17th, so I should get February 25th. If we were on February 26th, I should get March 25th.

I was not able to find anything about getting the next specific day of the month, but I am pretty sure that Python has something to make it easy.

Does anyone know how?

Upvotes: 4

Views: 623

Answers (3)

Ajit Vaze
Ajit Vaze

Reputation: 2704

def get_25_th_day(curr_date):

if curr_date.day <= 25:
    return datetime.date(curr_date.year, curr_date.month, 25)
else:
    new_month = curr_date.month + 1
    new_year = curr_date.year
    if curr_date.month == 12:
        new_month = 1
        new_year = curr_date.year + 1

    return datetime.date(new_year, new_month, 25)

print get_25_th_day(datetime.date.today())
>> 2016-02-25
print get_25_th_day(datetime.date(2016, 2, 25))
>> 2016-02-25
print get_25_th_day(datetime.date(2016, 2, 26))
>> 2016-03-25
print get_25_th_day(datetime.date(2016, 12, 26))
>> 2017-01-25

Upvotes: 1

matino
matino

Reputation: 17705

You could use python-dateutil for that and play with the rrule:

import datetime
from dateutil.rrule import * 

now = datetime.datetime.today().date()
days = rrule(MONTHLY, dtstart=now, bymonthday=25)
print (days[0])  # datetime.datetime(2016, 2, 25, 0, 0)
print (days[1])  # datetime.datetime(2016, 3, 25, 0, 0)

Upvotes: 3

Forge
Forge

Reputation: 6834

import datetime

def get_next_date_with_day(day_of_the_month):
    today_date = datetime.datetime.today()
    today = today_date.day
    if today == day_of_the_month:
        return today_date
    if today < day_of_the_month:
        return datetime.date(today_date.year, today_date.month, day_of_the_month)     
    if today > day_of_the_month:
        if today_date.month == 12:
            return datetime.date(today_date.year+1, 1, day_of_the_month) 
        return datetime.date(today_date.year, today_date.month+1, day_of_the_month) 

print get_next_date_with_day(25)
>>2016-02-25

Upvotes: 1

Related Questions