I have a csv file which contains several lines and in particular, column sending time. I wish to change the timedate formats from DD/MM/YYYYHH:MM:SS.DDDD to YYYYMMDD-HH:MM:SS for all values in column SendingTime.
CSV Example:
MsgType,CompID,SendingTime
AR ,SDF,16/08/2021 09:13:13.09934
I have found a code snippet on StackOverflow, and I'm trying the following to change the datetime format, however, to no avail and the below error. Any help would be most appreciated?
import csv
import re
from datetime import datetime
lines = []
# open file as read-only
with open('datetimeissue.csv', "r", newline='') as data:
reader = csv.reader(data)
# go over all of its rows, and the row's items and change
# items that match the date format
for row in reader:
for i, string in enumerate(row):
if re.match(r"\d+\/\d+\/\d+ \d+\:\d+\:\d+", string):
datetimeobject = datetime.strptime(string, '%d/%m/%Y %h:%m:%s')
new_string = datetimeobject.strftime('%Y-%m-%d-%h:%m:%s')
row[i] = new_string
print("Replaced", string, "with", new_string)
# save edited, and originally correct ones to new list
new_row = row
lines.append(new_row)
# write new rows by overwriting original file
with open('mynewoverwritten.csv', "w", newline='') as data:
writer = csv.writer(data)
writer.writerows(lines)
Error Extract
Traceback (most recent call last):
File "time.py", line 14, in <module>
datetimeobject = datetime.strptime(string, '%d/%m/%Y %h:%m:%s')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 354, in _strptime
(bad_directive, format)) from None
ValueError: 'h' is a bad directive in format '%d/%m/%Y %h:%m:%s'
YYYYMMDD-HH:MM:SSis a very unusual format that won't be recognized by any application. The standard format for dates is ISO8601 -YYYY-MM-DD HH:mm:ssorYYYY-MM-DDTHH:mm:ss