Search code examples
pythonstringlistnumbersextract

Python list with type strings


I have got a python list

Year= [‘1997JAN’, ‘1997FEB’, ‘1997MAR’‘1997APR’………………………’2021SEP’’2021OCT’]

I would like to extract only years from the above list but not the months

How can I extract only years?

Year = [1997,1997,1997,…………………2021,2021]

Solution

  • If you have these dates:

    dates = ['1997JAN', '1997FEB', '1997MAR','1997APR', '2022NOV']
    

    Just use this to extract years from dates:

    years = [int(x[:4]) for x in dates]