如何使用datetime在python中获取给定日期的下个月的同一天 [英] how to get the same day of next month of a given day in python using datetime

查看:918
本文介绍了如何使用datetime在python中获取给定日期的下个月的同一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用datetime.timedelta可以从给定日期获得几天的日期

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)

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

推荐答案

当然没有-如果今天的1月31日是下个月的同一天?显然,没有 right 解决方案,因为2月31日不存在,并且 datetime 模块不会在猜出没有适当解决方案而提出这个不可能的问题的用户认为(错误地)是显而易见的解决方案;-)。

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";-).

我建议:

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

这篇关于如何使用datetime在python中获取给定日期的下个月的同一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆