【问题标题】:How to format datetime values in csv file/column in python?如何在python的csv文件/列中格式化日期时间值?
【发布时间】: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:ssYYYY-MM-DDTHH:mm:ss
  • 嗨 Kanavos,这是问题之一 - 我无法在我们的 RH 系统上安装“第三方”库。否则,我真的会到处看到熊猫。
  • 仅供参考,如果您只想编辑 csv 并更改日期时间格式,有一个 Notepad++ 插件可以做到这一点github.com/BdR76/CSVLint
  • 感谢您提供的信息 - 但是,我必须在没有插件或第三方工具的情况下自动执行此过程。给出的答案很棒,因为我什至将它用于列表而不是 CSV 文件。
  • @Panagiotis 是的,时间格式很奇怪,但这是发送给客户/清算对手方的格式。这是 FIX 消息的摘录,因此我猜客户之间使用该标准。

标签: python-3.x regex csv replace


【解决方案1】:

%H:%M:%S(大写)是时间的格式字符串。如果您知道时间列,re 似乎不需要:

import csv
from datetime import datetime
 
with open('input.csv', "r", newline='') as inf, \
     open('output.csv', "w", newline='') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    writer.writerow(next(reader)) # copy header
    for row in reader:
        timestamp = datetime.strptime(row[2], '%d/%m/%Y %H:%M:%S.%f')
        row[2] = timestamp.strftime('%Y-%m-%d %H:%M:%S')
        writer.writerow(row)

【讨论】:

  • 非常感谢@Mark Tolonen。我可以确认这有效。
【解决方案2】:

ValueError: 'h' is a bad directive in format '%d/%m/%Y %h:%m:%s'

有一个很大的提示。错误是'h' 或接近它。在这种情况下,看起来是小写的“h”把你搞砸了。您是否尝试过使用'H'

datetime.strptime(string, '%d/%m/%Y %H:%M:%S')

【讨论】:

  • 嗨 Helix,我将时间变量更改为大写,但现在出现以下错误 ` datetimeobject = datetime.strptime(string, '%d/%m/%Y %H:%H:%S' ) 文件“/usr/lib64/python3.6/sre_parse.py”,第 759 行,在 _parse 中引发 source.error(err.msg, len(name) + 1) 从无 sre_constants.error: 重新定义组名 'H ' 作为第 5 组;是第 4 组在位置 116 `
猜你喜欢
  • 2018-07-23
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 2011-11-20
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
相关资源
最近更新 更多