Ben Smith
Ben Smith

Reputation: 85

Why can't I subtract one date period from the next and convert to an integer?

I am trying to determine whether a difference between two months is an even or odd number of months.

I used the command:

import pandas as pd
(pd.to_datetime('2019-01-01').to_period('M') - pd.to_datetime('2018-08-01').to_period('M')) % 2

This seems to work in python 3.6.7, but in another python 3.7.3 environment I get the error:

>>> import pandas as pd
>>> (pd.to_datetime('2019-01-01').to_period('M') - pd.to_datetime('2018-08-01').to_period('M')) % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'MonthEnd' and 'int'

I'm trying to work out what package would make the difference here, or if there is another way to do what I want that would work in both versions?

I took a look at my installed packages and there are a few version differences but I have no idea which would make the difference.

The environment that does not work has python 3.7.3, pandas 0.24.2, and numpy-base 1.16.2. The environment that works has python 3.6.7, pandas 0.22.0, but does not have any version of numpy-base. Both have python-dateutil 2.8.0 and numpy 1.16.2.

Upvotes: 3

Views: 1988

Answers (2)

jezrael
jezrael

Reputation: 862511

Problem is Period Subtraction in pandas 0.24+:

Subtraction of a Period from another Period will give a DateOffset. instead of an integer (GH21314)

Solution is attribut .n:

a = (pd.to_datetime('2019-01-01').to_period('m') - pd.to_datetime('2018-08-01').to_period('m'))

print (a)
<5 * MonthEnds>

print (a.n)
5

print (a.n % 2)
1

Upvotes: 6

U13-Forward
U13-Forward

Reputation: 71560

It's because in pandas 0.24.2, it returns:

<5 * MonthEnds>

Which isn't a integer, instead a MonthEnd object, so you would need to do .n, which gives you the actual number of 5:

print((pd.to_datetime('2019-01-01').to_period('M') - pd.to_datetime('2018-08-01').to_period('M')).n % 2)

Which outputs:

1

Upvotes: 3

Related Questions