python pandas DatetimeIndex如何获取月份的第一天?

时间:2018-07-02 06:26:18

标签: python pandas

begin = '2016-08-01'
end = '2018-07-01'
time_unit = 'm'
unit = 'month'

time_dict = {}
time_series = pd.DatetimeIndex(start=begin, end=end, freq=time_unit).tolist()

所有月份生成的DatetimeIndex开始于月份的结束日期。例如

2016-08-31 00:00:00

我怎么能得到

2016-08-01 00:00:00

1 个答案:

答案 0 :(得分:3)

month start frequencym更改为MS

begin = '2016-08-01'
end = '2018-07-01'
time_unit = 'MS'
unit = 'month'

time_dict = {}
time_series = pd.DatetimeIndex(start=begin, end=end, freq=time_unit).tolist()
print (time_series)
[Timestamp('2016-08-01 00:00:00', freq='MS'), Timestamp('2016-09-01 00:00:00', freq='MS'), Timestamp('2016-10-01 00:00:00', freq='MS'), Timestamp('2016-11-01 00:00:00', freq='MS'), Timestamp('2016-12-01 00:00:00', freq='MS'), Timestamp('2017-01-01 00:00:00', freq='MS'), Timestamp('2017-02-01 00:00:00', freq='MS'), Timestamp('2017-03-01 00:00:00', freq='MS'), Timestamp('2017-04-01 00:00:00', freq='MS'), Timestamp('2017-05-01 00:00:00', freq='MS'), Timestamp('2017-06-01 00:00:00', freq='MS'), Timestamp('2017-07-01 00:00:00', freq='MS'), Timestamp('2017-08-01 00:00:00', freq='MS'), Timestamp('2017-09-01 00:00:00', freq='MS'), Timestamp('2017-10-01 00:00:00', freq='MS'), Timestamp('2017-11-01 00:00:00', freq='MS'), Timestamp('2017-12-01 00:00:00', freq='MS'), Timestamp('2018-01-01 00:00:00', freq='MS'), Timestamp('2018-02-01 00:00:00', freq='MS'), Timestamp('2018-03-01 00:00:00', freq='MS'), Timestamp('2018-04-01 00:00:00', freq='MS'), Timestamp('2018-05-01 00:00:00', freq='MS'), Timestamp('2018-06-01 00:00:00', freq='MS'), Timestamp('2018-07-01 00:00:00', freq='MS')]