Reputation: 7004
I have a datetime instance declared as follows:
dtDate = datetime.datetime(2016,1,1,0,0)
How do I get the previous month and previous year from dtDate
?
e.g. something like:
dtDate.minusOneMonth()
# to return datetime.datetime(2015,12,1,0,0)
Upvotes: 11
Views: 20147
Reputation: 2187
To Manipulate an entire pandas series.
Use pd.DateOffset()
with .dt.to_period("M")
df['year_month'] = df['timestamp'].dt.to_period("M")
df['prev_year_month'] = (df['timestamp'] - pd.DateOffset(months=1)).dt.to_period("M")
If you want to go forward a month, set months=-1
.
Upvotes: 3
Reputation: 863701
You can use:
dtDate = datetime.datetime(2016,1,1,0,0)
print (dtDate - pd.DateOffset(months=1))
2015-12-01 00:00:00
print (dtDate - pd.DateOffset(years=1))
2015-01-01 00:00:00
Add s
is important, because if use year
only:
print (dtDate - pd.DateOffset(year=1))
0001-01-01 00:00:00
Upvotes: 20
Reputation: 36715
Use relativedelta
from dateutil
:
import datetime
import dateutil.relativedelta
dtDate = datetime.datetime(2016,1,1,0,0)
# get previous month
print ((dtDate+dateutil.relativedelta.relativedelta(months=-1)).month)
# get previous year
print ((dtDate+dateutil.relativedelta.relativedelta(years=-1)).year)
Output:
12
2015
Upvotes: 1
Reputation: 394459
You can use DateOffset
:
In [32]:
dtDate = dt.datetime(2016,1,1,0,0)
dtDate - pd.DateOffset(months=1)
Out[32]:
Timestamp('2015-12-01 00:00:00')
Upvotes: 3