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

icn*_*icn 46 python datetime date

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

daysafter = datetime.date.today() + datetime.timedelta(days=5)
Run Code Online (Sandbox Code Playgroud)

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

nos*_*klo 136

使用dateutil模块.它有相对时间增量:

import datetime
from dateutil import relativedelta
nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)
Run Code Online (Sandbox Code Playgroud)

美丽.

  • 哇它处理1月31日+ 1个月.它在2月的最后一天返回 (6认同)
  • dateutil太棒了.应该是标准的. (3认同)
  • pip install python-dateutil (2认同)

Ale*_*lli 31

当然没有 - 如果今天是1月31日,那将是"下个月的同一天"?!显然,没有正确的解决方案,二月以来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
Run Code Online (Sandbox Code Playgroud)

  • 谢谢Alex!我曾经在c#中使用Datetime.AddMonths()来解决这个问题.所以在询问转储问题之前我甚至没想过多少:).我在1月(28-31)用c#Datetime.AddMonths(1)做了一个测试,有趣的结果,我得到了2月28日.再次感谢Alex! (2认同)

小智 8

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

>>> import calendar
>>> calendar.nextmonth(year=2019, month=6)
(2019, 7)
>>> calendar.nextmonth(year=2019, month=12)
(2020, 1)
Run Code Online (Sandbox Code Playgroud)

但请注意,此函数并不是公共 API,而是在 calendar.Calendar.itermonthdays3() 方法内部使用。这就是它不检查给定月份值的原因:

>>> calendar.nextmonth(year=2019, month=60)
(2019, 61)
Run Code Online (Sandbox Code Playgroud)

Python 3.8中已经实现为内部函数。


Ch'*_*arr 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])
Run Code Online (Sandbox Code Playgroud)

  • 这是错误的。`next_month(datetime.date(2014,01,30))== datetime.date(2014,3,2)` (2认同)

zer*_*one 5

from calendar import mdays
from datetime import datetime, timedelta

today = datetime.now()
next_month_of_today = today + timedelta(mdays[today.month])
Run Code Online (Sandbox Code Playgroud)

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

  • 我真的希望这个解决方案起作用,但是使用 mdays 会破坏 2 月 4 日的一年... (2认同)

Dao*_*tor 5

这对我来说工作

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
Run Code Online (Sandbox Code Playgroud)

用法:

d = datetime.datetime.today()
print next_month_date(d)
Run Code Online (Sandbox Code Playgroud)