Home > Software design >  Python - Read file, rearrange date and change year from yy to yyyy
Python - Read file, rearrange date and change year from yy to yyyy

Time:10-15

I'm a Python newb. I've been learning a bit and am on files. So I have a program that I'm trying to write where it reads data from a file. Each line in the file is a date in the format dd-mmm-yy for example, 13-SEP-20. For simplicity, each year is assumed to be in the year 2000 or later. I need to replace SEP with 09 and rearrange the output to be mm-dd-yyyy. So the end result would be:

13-SEP-20 to 09-13-2020

So far, I have the below code. It's replacing values on each line using the dictionary for the month and rearranging to the correct order. Next, I need to change the year to 20nn but I'm not sure how to do that part.

import datetime 
months = {'JAN': '01', 'FEB': '02', 'MAR': '03', 'APR': '04', 'MAY': '05', 'JUN': '06', 
             'JUL': '07', 'AUG': '08', 'SEP': '09', 'OCT': '10', 'NOV': '11', 'DEC': '12'}
result_dic = {}
#replace mmm with mm int
with open('date_file.txt') as fh:
    giv_date=fh.read().splitlines()
    for line in giv_date:
        line = line.rstrip()
        for mon_alph, mon_num in months.items():
            if mon_alph in line:
                line = line.replace(mon_alph, mon_num)
                line = datetime.datetime.strptime(line,'%d-%m-%y')
                line = datetime.datetime.strftime(line,'%m-%d-%y')
        print(line)

The output from the above for the first few lines is:

09-13-20

09-11-20

09-10-20

08-27-19

08-24-20

Can someone assist me with how I can change the yy to yyyy? For simplicity I'd say possibly just adding 2000 to each year but I think that would possibly be too complex and there may be a simpler way? Thank you in advance for your assistance.

CodePudding user response:

Try %Y instead of %y. You can read more at python document about strftime. Basically the %y will return only 2 last digits, while %Y return 2021.

CodePudding user response:

To have 4 digits year representation replace last line with

line = datetime.datetime.strftime(line,'%m-%d-%Y')
  • Related