Reputation: 935
First and last dates of a time series are as follows:
firstday = transactions["Date"].head(1)
firstday
lastday = transactions["Date"].tail(1)
lastday
Dateindex
2017-12-30 2017-12-30
Name: Date, dtype: datetime64[ns]
Dateindex
2018-12-31 2018-12-31
Name: Date, dtype: datetime64[ns]
I want the following two things:
1) get firstday and lastday as "2017-12-30" and "2018-12-31" (strings), instead of dtype('<M8[ns]')
2) calculate the number of whole months between these dates (correct output would be 12 months)
Any ideas how to achieve these? Thank you.
Upvotes: 2
Views: 3336
Reputation: 371
Here is for you information
firstdayStr = str(firstday[0])
lastdayStr = str(lastday[0])
months = (lastday[0].year - firstday[0].year) * 12 + lastday[0].month - firstday[0].month
output
2017-12-30 00:00:00
2018-12-31 00:00:00
12
Upvotes: 0
Reputation: 863741
Select first and last value by Series.iat
:
firstday = transactions["Date"].iat[0]
lastday = transactions["Date"].iat[-1]
Alternative is use Index.get_loc
for position for column Date
with DataFrame.iat
:
firstday = transactions.iat[0, transactions.columns.get_loc('Date')]
lastday = transactions.iat[-1, transactions.columns.get_loc('Date')]
print (firstday)
2017-12-30 00:00:00
print (lastday)
2018-12-31 00:00:00
For difference convert timestamp to month period by Timestamp.to_period
and subtract:
diff = lastday.to_period('m') - firstday.to_period('m')
print (diff)
12
Upvotes: 6