Categories
Uncategorized

Reformatting dates – Python

This little script will reformat a series of dates in a file, from 22 April 1980 to a more compact 19800422 ([yyyymmdd]) ISO standard, using the re and time libraries.

Start with a file containing a series of dates

# date.txt
5 December 2012
28 January 1987
23 September 1997
21 June 1983
4 April 1979

Then this is the python code

#!/usr/bin/python

import re,time

# open input and output files
rDateFile=open("date.txt","r")
wOutputDate=open("newDate.txt","w")

for line in rDateFile:
    # we search for the different components
	dateComp=re.findall("(\d+) (\w+) (\d\d\d\d)",line)

    # put the components together and format them
	dateDivs=" ".join(dateComp[0])
	forDate=time.strptime(dateDivs,"%d %B %Y")

    # change the format to the compact ISO
	theDate=time.strftime("%Y%m%d",forDate)

    # write it in the output file
	wOutputDate.write(theDate+"\n")

# close all files
rDateFile.close()
wOutputDate.close()

Now the output file will read

# newDate.txt
20121205
19870128
19970923
19830621
19790404

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s