时间序列的开始和结束日期如下:
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]
我想要以下两件事:
1)以“ 2017-12-30”和“ 2018-12-31”(字符串)代替“ dtype('<M8[ns]')
”获得第一天和最后一天
2)计算这些日期之间的整个月的数量(正确的输出为12个月)
任何想法如何实现这些目标?谢谢。
答案 0 :(得分:6)
通过Series.iat
选择第一个和最后一个值:
firstday = transactions["Date"].iat[0]
lastday = transactions["Date"].iat[-1]
对于Index.get_loc
,列Date
的位置也使用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
对于差异,将时间戳记转换为月Timestamp.to_period
,然后减去:
diff = lastday.to_period('m') - firstday.to_period('m')
print (diff)
12
答案 1 :(得分:0)
这是给您的信息
firstdayStr = str(firstday[0])
lastdayStr = str(lastday[0])
months = (lastday[0].year - firstday[0].year) * 12 + lastday[0].month - firstday[0].month
输出
2017-12-30 00:00:00
2018-12-31 00:00:00
12