Converting a month's name to its corresponding number

date, python

Solution

Two possibilities:

- the datetime module

- DIY solution like you have

The python documentation is worth reading, you may find an easier way to do more than just answer this question.

As for the DIY solution it seems like you have a lot of repeat code, and there's no need for a regex. You could just do

for i, month in enumerate(months,1): 
    line.replace(month, str(i))

where `months` is a list of the months.

Problem

I have a file which contains a list of entries, with dates that contain "Jan","Feb","Mar" etc. I want 569207,ngph,RUN,512,16,2012-Jan-23 01:42,2012-04-23 10:53 to become 569207,ngph,RUN,512,16,2012-01-23 01:42,2012-04-23 10:53. I've written the following: ``` for line in f: if re.search(r'Jan', line): f1.write(line.replace('Jan', '01')) elif re.search(r'Feb', line): f1.write(line.replace('Feb', '02')) elif re.search(r'Mar', line): f1.write(line.replace('Mar', '03')) elif re.search(r'Apr', line): f1.write(line.replace('Apr', '04')) elif re.search(r'May', line): f1.write(line.replace('May', '05')) elif re.search(r'Jun', line): f1.write(line.replace('Jun', '06')) elif re.search(r'Jul', line): f1.write(line.replace('Jul', '07')) elif re.search(r'Aug', line): f1.write(line.replace('Aug', '08')) elif re.search(r'Sep', line): f1.write(line.replace('Sep', '09')) elif re.search(r'Oct', line): f1.write(line.replace('Oct', '10')) elif re.search(r'Nov', line): f1.write(line.replace('Nov', '11')) elif re.search(r'Dec', line): f1.write(line.replace('Dec', '12')) ``` which works, but is there a cleaner method? I want it to iterate through an entire file of about 100 lines and automatically change the month to a number. Thanks.

Original source

Related problems