python-3.x - 如何在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'
解决方案
%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)
推荐阅读
- linux - 如何在bash中grep和替换字符串
- node.js - 如何在 sinon 中测试 axios 的调用获取?
- python - 我在从 Django 模型中传递模板中的特定图像时遇到问题
- javascript - Javascript在具有相同类但变量不同的多个div中运行函数
- javascript - 我想通过获取成功注册后设置的 URL 参数来更改或删除我的 html 元素
- python - 无法通过 pip 在 macOS Big Sur 上安装 jamspell?
- javascript - Nodejs / ExpressJs - 发出并行 api 请求以执行同步/异步作业
- amazon-web-services - AWS Fargate 的最大运行时间为 120 秒?
- python-3.x - 两个独立源的多线程问题
- php - PHP 8.0.8 + Laravel 8.4 全新安装子 1035 在信号 11 上退出(SIGSEGV - 核心转储)