python怎么加一个月,有没有一种简单的方法可以在Python中将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)

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.

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.

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

解决方案

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)

or you can start using relativedelta

use_date = use_date+relativedelta(months=+1)

use_date = use_date+relativedelta(years=+1)

for the last day of next month:

use_date = use_date+relativedelta(months=+1)

use_date = use_date+relativedelta(day=31)

Right now this will provide 29/02/2016

for the penultimate day of next month:

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

This is by no means an exhaustive list of what is available.

Documentation is available here: https://dateutil.readthedocs.org/en/latest/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值