Escribí un script de Python y un script de Bash que deberían hacer lo que quieras.
Aquí hay una secuencia de comandos de Python que convierte todos los campos de tiempo -de un formato a otro, como se especifica en la pregunta:
#!/usr/bin/env python3
# -*- coding: ascii -*-
"""reformat_time.py
Change date format from:
MM/DD/YYYY HH:MM:SS am/pm
to:
YYYY-MM-DD HH:MM:SS
in a CSV file
"""
import csv
from datetime import date
from datetime import datetime
import sys
# Open the file (taken as a command-line argument)
with open(sys.argv[1], 'r') as csvfile:
# Parse the CSV data
csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
# Iterate over the rows
for row in csvreader:
# Iterate over the columns of each row
for index, col in enumerate(row):
# Try to parse and convert each column
try:
_datetime = datetime.strptime(col, "%m/%d/%Y %H:%M:%S %p")
newcol = _datetime.strftime("%Y-%m-%d %H:%M:%S")
# If parsing fails, leave the column unchanged
except ValueError:
newcol = col
# Update the column value
row[index] = newcol
# Output the updated row
print(','.join(row))
Supongamos que su archivo CSV se llama data.csv
y contiene la siguiente línea (tomada de su publicación):
Victor,5555555,12/6/2013 10:26:32 AM,Colosseum,1,12/8/2013 1:05:45 PM
Entonces podrías ejecutar el script así:
python reformat_time.py data.csv
Esto produciría el siguiente resultado:
Victor,5555555,2013-12-06 10:26:32,Colosseum,1,2013-12-08 01:05:45
Y aquí hay un script Bash que usa la utilidad GNU date
que tiene (casi )el mismo efecto:
#!/bin/bash
# reformat_time.sh
# Loop over the lines of the file
while read -r line; do
# Extract the field values for each row
Name="$(echo ${line} | cut -d, -f1)";
Phone="$(echo ${line} | cut -d, -f2)";
SalesDate="$(echo ${line} | cut -d, -f3)";
Venue="$(echo ${line} | cut -d, -f4)";
NoOfUnits="$(echo ${line} | cut -d, -f5)";
ModifiedDate="$(echo ${line} | cut -d, -f6)";
# Convert the time-fields from the old format to the new format
NewSalesDate="$(date -d "${SalesDate}" "+%Y-%m-%d %H:%M:%S")";
NewModifiedDate="$(date -d "${ModifiedDate}" "+%Y-%m-%d %H:%M:%S")";
# Output the updated row
echo "${Name},${Phone},${NewSalesDate},${Venue},${NoOfUnits},${NewModifiedDate}";
done < "$1"
Podría ejecutarlo así:
bash reformat_time.sh data.csv
Y produciría el siguiente resultado:
Victor,5555555,2013-12-06 10:26:32, Colosseum,1,2013-12-08 13:05:45
Tenga en cuenta que el script Bash es mucho más frágil. No maneja errores -y solo afecta los campos 3 y 6. También conserva el espacio en blanco -que rodea el separador de campo, lo que no hace la secuencia de comandos de Python anterior.
Знак $ означает :поиск шаблона в конце строки Шаблон '\r\n'; значение :\r (возврат каретки )\n (новая строка)
Квадратные скобки [ ] используются для заключения искомого в отдельной строке
Эта команда удаляет все байты возврата каретки и перевода строки из переменной line
.
Это Bash (и zsh, а ksh )расширение расширения параметра:${line//XYZ}
заменяет все совпадения шаблона XYZ
в $line
ничем.
Шаблон [$'\r\n']
состоит из двух компонентов:[...]
соответствует любому из символов внутри него . $'\r\n'
— это ANSI -C, цитирующий(другое расширение ), и расширяется до байтов возврата каретки(\r
)и перевода строки (\n
), поэтому [$'\r\n']
— это [...]
с кареткой return и перевод строки внутри него, и поэтому соответствует им обоим.
Полное руководство по командам оболочки , операторам, скобкам и т. д. находится здесь и является частью спецификации POSIX/SUS/IEEE 1003.1. Справочное руководствоBash находится здесь .