[SOLVED] Convert a column of timestamps into periods in pandas


I have a column of timestamps that need to be converted into period (‘Month’). e.g.

1985-12-31 00:00:00 to 1985-12

Pandas has a .to_period() function, but:

  • pd.DatetimeIndex.to_period only works on a timestamp index, not column. So you can only have a period index, but not a period column?
  • and that function only work if timestamps are the only index, i.e. not if timestamps are part of a multIndex.

Anyway how do I use this on an arbitary Pandas column, not just a tiemstamp index or period index?


I came across this thread today, and after further digging found that Pandas .15 affords an easier option use .dt, you can avoid the step of creating an index and create the column directly. You can use the following to get the same result:

df[1] = df[0].dt.to_period('M')

Answered By – mattvivier

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *