Sav K.
Sav K.

Reputation: 25

How to change the format of date from YYYY-MM-DD to YYYY-MM

I have a list of date in the format yyyy-mm-dd but I want to group them into a dictionary with the format yyyy-mm. Does anybody know how?

date_list = [
'2021-05-01', 
'2021-03-25', 
'2021-04-14',
'2021-04-18',
'2021-05-21',
'2021-05-17']

What I want

year_month = [
'2021-05',
'2021-03',
'2021-04',
'2021-04',
'2021-05',
'2021-05']

Upvotes: 1

Views: 55

Answers (1)

bn_ln
bn_ln

Reputation: 1683

Quick and easy solution is just to use string slicing

year_month = [date[:7] for date in date_list]

Upvotes: 2

Related Questions