当前位置: 动力学知识库 > 问答 > 编程问答 >

how to get the same day of next month of a given day in python using datetime

问题描述:

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!

网友答案:

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
网友答案:

Use dateutil module. It has relative time deltas:

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

Beautiful.

网友答案:
import calendar, datetime

def next_month ( date ):
    """return a date one month in advance of 'date'. 
    If the next month has fewer days then the current date's month, this will return an
    early date in the following month."""
    return date + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])
网友答案:
from calendar import mdays
from datetime import datetime, timedelta

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

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

网友答案:
from datetime import timedelta
try:
    next_month = (x.replace(day=28) + timedelta(days=7)).replace(day=x.day)
except ValueError:  # assuming January 31 should return last day of February.
    next_month = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
网友答案:

This is how I solved it.

from datetime import date
try:
    (year, month) = divmod(date.today().month, 12)
    next_month = date.today().replace(year=date.today().year+year, month=month+1)
except ValueError:
    # This day does not exist in next month

You can skip the try/catch if you only want the first day in next month by setting replace(year=date.today().year+year, month=month, day=1). This will always be a valid date since we have caught the month overflow using divmod.

网友答案:

This work for me

import datetime
import calendar


def next_month_date(d):
    _year = d.year+(d.month//12)
    _month =  1 if (d.month//12) else d.month + 1
    next_month_len = calendar.monthrange(_year,_month)[1]
    next_month = d
    if d.day > next_month_len:
        next_month = next_month.replace(day=next_month_len)
    next_month = next_month.replace(year=_year, month=_month)
    return next_month

usage:

d = datetime.datetime.today()
print next_month_date(d)
分享给朋友:
您可能感兴趣的文章:
随机阅读: