【发布时间】:2021-10-25 18:57:22
【问题描述】:
我有一个 csv 文件,其中包含多行,尤其是列发送时间。我希望将时间日期格式 从 DD/MM/YYYYHH:MM:SS.DDDD 更改为 YYYYMMDD-HH:MM:SS SendingTime 列中的值。
CSV 示例:
MsgType,CompID,SendingTime
AR ,SDF,16/08/2021 09:13:13.09934
我在 StackOverflow 上找到了一个代码 sn-p,我正在尝试以下方法来更改日期时间格式,但是无济于事,并出现以下错误。任何帮助将不胜感激?
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)
错误提取
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'
【问题讨论】:
-
不使用正则表达式,而是使用众多 CSV 库之一来读取数据并以新格式再次保存。大多数库实际上也会解析日期,只允许您指定新格式。
YYYYMMDD-HH:MM:SS是一种非常不寻常的格式,任何应用程序都无法识别。日期的标准格式是 ISO8601 -YYYY-MM-DD HH:mm:ss或YYYY-MM-DDTHH:mm:ss -
嗨 Kanavos,这是问题之一 - 我无法在我们的 RH 系统上安装“第三方”库。否则,我真的会到处看到熊猫。
-
仅供参考,如果您只想编辑 csv 并更改日期时间格式,有一个 Notepad++ 插件可以做到这一点github.com/BdR76/CSVLint
-
感谢您提供的信息 - 但是,我必须在没有插件或第三方工具的情况下自动执行此过程。给出的答案很棒,因为我什至将它用于列表而不是 CSV 文件。
-
@Panagiotis 是的,时间格式很奇怪,但这是发送给客户/清算对手方的格式。这是 FIX 消息的摘录,因此我猜客户之间使用该标准。
标签: python-3.x regex csv replace