Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the nth day of the next month in Python?

I am trying to get the date delta by subtracting today's date from the nth day of the next month.

delta = nth_of_next_month - todays_date
print delta.days

How do you get the date object for the 1st (or 2nd, 3rd.. nth) day of the next month. I tried taking the month number from the date object and increasing it by 1. Which is obviously a dumb idea because 12 + 1 = 13. I also tried adding one month to today and tried to get to the first of the month. I am sure that there is a much more efficient way of doing this.

like image 457
Johnston Avatar asked Dec 05 '22 07:12

Johnston


2 Answers

The dateutil library is useful for this:

from dateutil.relativedelta import relativedelta
from datetime import datetime

# Where day is the day you want in the following month
dt = datetime.now() + relativedelta(months=1, day=20)
like image 108
Jon Clements Avatar answered Dec 08 '22 06:12

Jon Clements


This should be straightforward unless I'm missing something in your question:

import datetime

now = datetime.datetime.now()
nth_day = 5
next_month = now.month + 1 if now.month < 12 else 1 # February
year = now.year if now.month < 12 else now.year+1
nth_of_next_month = datetime.datetime(year, next_month, nth_day)
print(nth_of_next_month)

Result:

2014-02-05 00:00:00

Using dateutil as suggested in another answer is a much better idea than this, though.

like image 32
senshin Avatar answered Dec 08 '22 06:12

senshin