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
import datetime
from dateutil import relativedelta
nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)
Run Code Online (Sandbox Code Playgroud)
美丽.
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)
小智 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中已经实现为内部函数。
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)
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。试试这个。祝你好运。
这对我来说工作
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)