Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding 1 month to February 28th results in March 28th #53

Closed
pganssle opened this issue Mar 3, 2015 · 1 comment
Closed

Adding 1 month to February 28th results in March 28th #53

pganssle opened this issue Mar 3, 2015 · 1 comment

Comments

@pganssle
Copy link
Member

pganssle commented Mar 3, 2015

Migrated from launchpad issue #1292043.

Quoting Florian Müller on 2014-03-13

I actually don't know, whether this is a bug but it was not the behavior I expected so I report it.

Consider the following code:

>>> datetime.date(2014,12,31) + relativedelta(months=1) + relativedelta(months=1) + relativedelta(months=1)
datetime.date(2015, 3, 28)
>>> datetime.date(2014,12,31) + relativedelta(months=3)
datetime.date(2015, 3, 31)

I really expected both examples to result in the same date.

Or want may I do to achieve the same result (other than manually check for february 28th/29th)

@pganssle
Copy link
Member Author

pganssle commented Mar 4, 2015

@jajadinimueter (assuming you are the same here and on LP - seems likely):

Thanks for reporting this. This is an order of operations issue, and is the expected behavior. The problem is that any addition between a datetime and a relativedelta has to return a valid date. So in your example:

>>> datetime.date(2014,12,31) + relativedelta(months=1) + relativedelta(months=1) + relativedelta(months=1)
datetime.date(2015, 3, 28)

This is the same as:

>>> (((datetime.date(2014,12,31) + relativedelta(months=1)) + relativedelta(months=1)) + relativedelta(months=1))
datetime.date(2015, 3, 28)

So the first operation resolves to datetime.date(2014, 1, 31), the second one resolves to datetime.date(2014, 2, 28) (because Feb 31 is not a valid date), and the third resolves to datetime.date(2014, 3, 28). I'm not sure what your specific use case is (e.g. why you want to use 3 relativedeltas instead of one), but in your example, you can fix it by doing all the relativedelta addition first:

>>> datetime.date(2014,12,31) + (relativedelta(months=1) + relativedelta(months=1) + relativedelta(months=1))
datetime.date(2015, 3, 31)

@pganssle pganssle closed this as completed Mar 4, 2015
@pganssle pganssle added wontfix and removed bug labels Mar 4, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant