Last active
January 28, 2016 03:22
-
-
Save jdunic/3274d7d9c63640e75b60 to your computer and use it in GitHub Desktop.
Changing date format of csv headers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # From a list of bad dates: | |
| import csv | |
| from datetime import datetime | |
| input_file = "bad_dates.csv" | |
| output_file = "good_dates.csv" | |
| with open(output_file, 'wb') as open_file: | |
| writer = csv.writer(open_file, dialect='excel') | |
| with open(input_file, 'rU') as csvfile: | |
| reader = csv.DictReader(csvfile) | |
| for row in csvreader: | |
| bad_dt = row['date'] | |
| bad_dt = datetime.strptime(bad_dt, "%m%d%Y") | |
| good_dt = datetime.strftime(bad_dt, "%Y%m%d") | |
| writer.writerow( [good_dt] ) | |
| # To work with the original file: | |
| import csv | |
| from datetime import datetime | |
| input_file = "bad_dates2.csv" | |
| output_file = "good_dates2.csv" | |
| with open(input_file, 'rU') as csvfile: | |
| reader = csv.DictReader(csvfile) | |
| new_names = [] | |
| index = -1 | |
| for fn in reader.fieldnames: | |
| index += 1 | |
| try: | |
| bad_dt = datetime.strptime(fn, "%m%d%Y") | |
| fn = datetime.strftime(bad_dt, "%Y%m%d") | |
| reader.fieldnames[index] = fn | |
| except ValueError as e: | |
| reader.fieldnames[index] = fn | |
| reader.fieldnames[0:3] = ('Site', 'Latitude', 'Longitude') | |
| with open(output_file, 'wb') as open_file: | |
| writer = csv.DictWriter(open_file, fieldnames = reader.fieldnames) | |
| writer.writeheader() | |
| for row in reader: | |
| writer.writerow(row) | |
| # Notice that at the bottom, unlike the last csv writing that we did, here we | |
| # are using csv.DictWriter. Dictionaries in Python are not ordered, that is, | |
| # when you print out a dictionary, you just get a list in alphabetical or | |
| # numerical order. Using DictWriter here will however, allow Python to write our | |
| # csv in the correct order, because Python maps each value in the csv file to | |
| # the correct header in the dictionary that was created in DictReader. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment