Skip to content

Instantly share code, notes, and snippets.

@moio
Created January 17, 2025 10:41
Show Gist options
  • Save moio/2dd4726b88bb1ddca4e9ce691ed12098 to your computer and use it in GitHub Desktop.
Save moio/2dd4726b88bb1ddca4e9ce691ed12098 to your computer and use it in GitHub Desktop.
Script to convert the date format in a CSV from an arbitrary format to ISO 8601
import sys
import csv
from datetime import datetime
# Replaces a CSV column reformatting the date according to ISO 8601 standard with millis
# Usage: python fix_date_format.py < input.csv > output.csv
COLUMN_TO_REFORMAT_INDEX = 0
INPUT_FORMAT = '%d.%m.%Y, %H:%M:%S.%f'
def reformat_date(date_str):
# Parse the date and time from the input format
date_time_obj = datetime.strptime(date_str, '%d.%m.%Y, %H:%M:%S.%f')
# Format the date and time to the desired output format
return date_time_obj.strftime('%Y-%m-%d-T%H:%M:%S.%f')[:-3]
reader = csv.reader(sys.stdin)
writer = csv.writer(sys.stdout)
# Skip the first row (header)
header = next(reader)
writer.writerow(header)
# convert first column
for row in reader:
if row:
row[COLUMN_TO_REFORMAT_INDEX] = reformat_date(row[COLUMN_TO_REFORMAT_INDEX])
writer.writerow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment