4

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?

forvas
  • 9,801
  • 7
  • 62
  • 158
  • 2
    You should look up the package _**datetime**_ Then, with a datetime object referring to a specific date, you could use a pretty simple routine to check whether the day is greater than 25 and, if so, increment the month and set the day at 25; on the other hand, if lesser than 25, just update it to 25. Take a look at this: [datetime](http://stackoverflow.com/questions/311627/how-to-print-date-in-a-regular-format-in-python) – Gabriel S. Gusmão Feb 17 '16 at 11:03
  • What do you want to get if you want the next 30th day of the month? – jfs Feb 17 '16 at 17:45
  • Does it matter whether such day exists e.g., Feb 30? Does it matter whether such day exists in your local timezone e.g., there is no 30 December 2011 in Tokelau (`Pacific/Fakaofo` tzid)? – jfs Feb 17 '16 at 17:50

3 Answers3

3

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)
matino
  • 17,199
  • 8
  • 49
  • 58
1
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
Forge
  • 6,538
  • 6
  • 44
  • 64
1
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
Ajit Vaze
  • 2,686
  • 2
  • 20
  • 24