有没有一种简单的方法可以在Python中将datetime对象增加一个月? [英] Is there a simple way to increment a datetime object one month in Python?

查看:1213
本文介绍了有没有一种简单的方法可以在Python中将datetime对象增加一个月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图找到一种将datetime对象增加一个月的方法。但是,根据这个问题

So I am trying to find a way to increment a datetime object by one month. However, it seems this is not so simple, according to this question.

我希望获得类似的东西:

I was hoping for something like:

import datetime as dt

now = dt.datetime.now()
later = now + dt.timedelta(months=1)

但这不起作用。我还希望能够在下个月的同一天(或最近的替代时间)去。例如,在1月1日设置的日期时间对象将增加到2月1日,而在2月28日设置的日期时间对象将增加到3月31日,而不是3月28日。

But that doesn't work. I was also hoping to be able to go to the same day (or the closest alternative) in the next month if possible. For example, a datetime object set at January 1st would increment to Feb 1st whereas a datetime object set at February 28th would increment to March 31st as opposed to March 28th or something.

要明确的是,2月28日(通常)会映射到3月31日,因为它是该月的最后一天,因此应该转到该日期的最后一天下个月的一个月。否则,它将是直接链接:增量应转到下个月的同一天。

To be clear, February 28th would (typically) map to March 31st because it is the last day of the month, and thus it should go to the last day of the month for the next month. Otherwise it would be a direct link: the increment should go to the day in the next month with the same numbered day.

在当前版本的Python中,有没有简单的方法可以做到这一点?

Is there a simple way to do this in the current release of Python?

推荐答案

从dateutil.relativedelta import中检出 *
为日期添加特定时间,您可以继续使用 timedelta 表示简单的东西,即

Check out from dateutil.relativedelta import * for adding a specific amount of time to a date, you can continue to use timedelta for the simple stuff i.e.

use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)

或者您可以开始使用 relativedelta

use_date = use_date+relativedelta(months=+1)

use_date = use_date+relativedelta(years=+1)

下个月的最后一天:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)

右现在,这将在下个月倒数第二天提供2016年2月29日

Right now this will provide 29/02/2016

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)

下个月的最后一个星期五:

last Friday of the next month:

use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))

下个月的第二个星期二:

2nd Tuesday of next month:

new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))

这绝不是详尽的清单可用。
文档位于此处: https://dateutil.readthedocs.org/en/latest/

This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/

这篇关于有没有一种简单的方法可以在Python中将datetime对象增加一个月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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