Kshitij Kshitij - 1 month ago 7
Python Question

How to change date format in delimited file using python?

I have a pipe delimited text file with records like:

ABC|1234|10/26/2016|PQRS|02/27/2016|

GHI|4321|02/27/2016|UOIP|10/26/2016|


Looking for a way to change
mm/dd/yyyy
format to be changed to
yyyy-mm-dd

Answer

Use the following approach with strptime and strftime functions from datetime module:

import datetime

# while iterating through the lines with a given format
# ...
line = 'ABC|1234|10/26/2016|PQRS|02/27/2016|'

line = '|'.join([item if k not in [2,4] else datetime.datetime.strptime(item, '%m/%d/%Y').strftime("%Y-%m-%d")
        for k, item in enumerate(line.split('|'))])

print(line)

The output(for exemplary line):

ABC|1234|2016-10-26|PQRS|2016-02-27|

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

Comments