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

Question:

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']
Asked By: Sav K.

||

Answers:

Quick and easy solution is just to use string slicing

year_month = [date[:7] for date in date_list]
Answered By: bn_ln
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.