Home > Software design >  Converting month in string to numeric in Python
Converting month in string to numeric in Python

Time:11-03

There is a list of dates in a form combining month as a string (e.g, Jan) and date as a number (e.g., 13).

a = ['20January', '14March', '3December', '1May', '17June', '2February']

How can I this list to Month-day format (e.g., 0120, 0314, 1203, ...) using datetime.striptime?

CodePudding user response:

Code

import datetime

a = ['20January', '14March', '3December', '1May', '17June', '2February']

for entry in a:
    print(datetime.datetime.strptime(entry, '%d%B').strftime('%m%d'))

Output

0120
0314
1203
0501
0617
0202

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

CodePudding user response:

just thought what happens when input would have make no sense, seems to cover that well

import datetime

a = ['20January', '14March', '3December', '1May', '17June', '2February','31February','ekldnwld']

for entry in a:
    try:
        print(datetime.datetime.strptime(entry, '%d%B').strftime('%m%d'))
    except ValueError as ve:
        print(ve)
0120
0314
1203
0501
0617
0202
day is out of range for month
time data 'ekldnwld' does not match format '%d%B'
  • Related