如何使用datetime在python中获取给定日期下个月的同一天

时间:2010-02-12 05:59:55

标签: python datetime date

我知道使用datetime.timedelta我可以在给定日期之前获得某些日子的日期

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

但似乎没有datetime.timedelta(month=1)

9 个答案:

答案 0 :(得分:120)

使用dateutil模块。它有relative time deltas

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

美丽。

答案 1 :(得分:29)

当然没有 - 如果今天是1月31日,那么“下个月的同一天”会是什么?!显然没有正确的解决方案,因为2月31日不存在,而datetime模块播放“猜测用户如何构成这个不可能的问题一个正确的解决方案认为(错误的)是明显的解决方案“; - )。

我建议:

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

答案 2 :(得分:6)

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])

答案 3 :(得分:3)

from calendar import mdays
from datetime import datetime, timedelta

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

我不想导入dateutil。试一试。祝你好运。

答案 4 :(得分:1)

这项工作对我来说

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

用法:

d = datetime.datetime.today()
print next_month_date(d)

答案 5 :(得分:1)

您可以使用calendar.nextmonth(来自Python 3.7)。

>>> import calendar
>>> calendar.nextmonth(year=2019, month=6)
(2019, 7)
>>> calendar.nextmonth(year=2019, month=12)
(2020, 1)

答案 6 :(得分:0)

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)

答案 7 :(得分:0)

这就是我解决它的方法。

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

如果您只想设置replace(year=date.today().year+year, month=month, day=1)下个月的第一天,则可以跳过try / catch。这将始终是一个有效的日期,因为我们使用divmod抓住了月份溢出。

答案 8 :(得分:0)

通过查看32天中的哪个月,您可以弄清楚这是一个月的最后一天以及下个月是否存在日期。这是因为连续两个月中至少有一个包含31天

from datetime import date, timedelta

def in_a_month(d):
    in_32_days = d + timedelta(32)
    if (in_32_days.month - d.month) % 12 > 1:
        return in_32_days - timedelta(in_32_days.day)
    else:
        return date(in_32_days.year, in_32_days.month, d.day)

或者,如果您需要一个解决方案来添加或删除任意数量的月份

from datetime import date, timedelta

def last_day_in_month(a_date, months_forward = 0):
    month_index = a_date.year * 12 + a_date.month + months_forward
    y = month_index // 12
    m = (month_index % 12) + 1
    return date(y, m, 1) - timedelta(1)

def add_month(a_date, months = 1):
    is_last_day = a_date == last_day_in_month(a_date)
    last_in_target_month = last_day_in_month(a_date, months)
    if is_last_day or a_date.day > last_in_target_month.day:
        return last_in_target_month
    else:
        return last_in_target_month.replace(day = a_date.day)