1

I have a date column like this.

2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-29
2012-01-29
2012-01-29
2012-01-29
2012-01-29
2012-01-29

....
2016-12-31
2016-12-31
2016-12-31
2016-12-31

I want to convert it into any of the below format: i.e get the unique yyyy-mm

2012-01  or 2012-Jan   or Jan
2012-02  or 2012-Feb   or Feb
2012-03 
...
2016-12   or 2012-Dec  or Dec
cs95
  • 379,657
  • 97
  • 704
  • 746
Dhiraj Kumar
  • 93
  • 1
  • 6
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [On topic](http://stackoverflow.com/help/on-topic), [how to ask](http://stackoverflow.com/help/how-to-ask), and [... the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is not a design, coding, research, or tutorial resource. However, if you follow whatever resources you find on line, make an honest coding attempt, and run into a problem, you'd have a good example to post. – Prune Dec 28 '18 at 20:16

1 Answers1

2

Use DatetimeIndex.to_period:

pd.DatetimeIndex(df['date']).to_period('M').unique()
#  PeriodIndex(['2012-01', '2016-12'], dtype='period[M]', name='date', freq='M')

If month names are needed, use strftime:

df['date'].dt.strftime('%Y-%b').unique()
# array(['2012-Jan', '2016-Dec'], dtype=object)

If Series format is necessary, use drop_duplicates:

df['date'].dt.strftime('%Y-%b').drop_duplicates()

0     2012-Jan
18    2016-Dec
Name: date, dtype: object
cs95
  • 379,657
  • 97
  • 704
  • 746
  • @W-B Wow, did not notice such a thread... interesting indeed! – cs95 Dec 28 '18 at 19:51
  • @W-B Add yourself to that list please, you are one of us and have been so for a long time. – cs95 Dec 28 '18 at 19:53
  • 1
    Nope I only have limit years experience with python and learn from your guys :-) – BENY Dec 28 '18 at 19:54
  • @W-B Thanks man, :) I don't know about the others but I could definitely say the same, have learned so much from all of you and am so grateful to be a part of this community – cs95 Dec 28 '18 at 19:58
  • @W-B btw, have you seen [this](https://stackoverflow.com/a/53954986/4909087) yet? – cs95 Dec 28 '18 at 19:58