首页 > 解决方案 > 如何在python的csv文件/列中格式化日期时间值?

问题描述

我有一个 csv 文件,其中包含几行,特别是列发送时间。我希望将 SendingTime 列中所有值的时间日期格式从 DD/MM/YYYYHH:MM:SS.DDDD 更改 YYYYMMDD-HH:MM:SS

CSV 示例:

MsgType,CompID,SendingTime    
AR ,SDF,16/08/2021 09:13:13.09934

我在 StackOverflow 上找到了一个代码片段,我正在尝试以下方法来更改日期时间格式,但是无济于事,并且出现以下错误。非常感激任何的帮助?

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'

标签: python-3.xregexcsvreplace

解决方案


%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)

推荐阅读