2

I'm trying to get the difference in years between two dates (in string) 'start date' and 'end date' from a list, but I noticed the list of dates are not in the right format. After trying to convert to the same format, the output keeps changing the year to 2021 which is wrong. Here is my code and output

start_date= ['18-Aug', '12-Aug', 'Nov-19', 'Oct-17', '19-Apr', 'Mar-15', '12-Jul', 'Jul-15', '13-May', '13-Oct']

for i in range(len(start_date)):
    print(dateutil.parser.parse(start_date[i]).strftime("%y-%b"))

Output:

21-Aug
21-Aug
21-Nov
21-Oct
21-Apr
21-Mar
21-Jul
21-Jul
21-May
21-Oct

Expected output should be:

18-08
12-08 
19-11 
17-10 
19-04 
15-03
12-07 
15-07 
13-05
13-10
Moresky
  • 77
  • 4

1 Answers1

2

You have used the wrong format, %y-%b for the output. Also, you do not need to use dateutil library. You can do it by using the standard datetime library as shown in this answer.

from datetime import datetime


def try_parsing_date(text):
    for fmt in ('%b-%d', '%d-%b'):
        try:
            return datetime.strptime(text, fmt)
        except ValueError:
            pass
    raise ValueError('no valid date format found')


start_date = ['18-Aug', '12-Aug', 'Nov-19', 'Oct-17', '19-Apr', 'Mar-15', '12-Jul', 'Jul-15', '13-May', '13-Oct']

for text in start_date:
    print(try_parsing_date(text).strftime("%d-%m"))

Output:

18-08
12-08
19-11
17-10
19-04
15-03
12-07
15-07
13-05
13-10
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 3
    Nice to see an answer of mine getting some use :) (although in this case it's overkill as they only have one input format...) but yeah... `dateutil` isn't necessary here. – Jon Clements Oct 31 '21 at 08:42