views:

183

answers:

6

i know using datetime.timedelta i can get the date of some days away form given date

daysafter = datetime.date.today() + datetime.timedelta(days=5)

but seems no datetime.timedelta(months=1)

!Thanks for any help!

A: 

Doomsday Algorithm

TheMachineCharmer
The OP's question is nothing to do with the day of the week.
John Machin
A: 
today = datetime.date.today()
daysafter = today.replace(month=today.month+1)

This won't work if the day doesn't make sense for the following month. What do you want to happen if you try to take the same day for the next month if the day is 30th of January?

gnibbler
+4  A: 

Of course there isn't -- if today's January 31, what would be "the same day of the next month"?! Obviously there is no right solution, since February 31 does not exist, and the datetime module does not play at "guess what the user posing this impossible problem without a right solution thinks (wrongly) is the obvious solution";-).

I suggest:

try:
  nextmonthdate = x.replace(month=x.month+1)
except ValueError:
  if x.month == 12:
    nextmonthdate = x.replace(year=x.year+1, month=1)
  else:
    # next month is too short to have "same date"
    # pick your own heuristic, or re-raise the exception:
    raise
Alex Martelli
Thanks Alex! I used to use Datetime.AddMonths() in c# for this question. So i didn't even think much before asking the dump question :).I did a test with c# Datetime.AddMonths(1) for Jan (28-31), interesting results, i got 5 Feb 28.Thanks again Alex!
xlione
+1  A: 

Use dateutil module. It has relative time deltas:

import datetime
import dateutil
nextmonth = datetime.date.today() + dateutil.relativedelta.relativedelta(months=1)

Beautiful.

nosklo
A: 
import calendar.mdays
from datetime import datetime, timedelta

today = datetime.now()
next_month_of_today = today + timedelta(calendar.mdays[today.month])

I don't want to import dateutil. Have a try this. Good luck.

zerone
A: 

@zerone

""" import calendar.mdays

from datetime import datetime, timedelta

today = datetime.now()

next_month_of_today = today + timedelta(calendar.mdays[today.month]) """

I'd like to point that this is not correct. How about if today is "datetime.date(2000,1,31)"? According to your code 'next_month_of_today' will be (2000,3,2).

Found a bettr one from http://is.gd/g7yet:

import datetime

def nextmo(d):

mo = d.month 
yr = d.year 
nm = datetime.date(yr,mo,1)+datetime.timedelta(days=31) 
return nm.strftime('%b%y').upper() 
vvoody