值错误:时间数据“”与格式“%d%m%Y%H:%m:%S”不匹配

2024-09-27 00:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是:

  1. Delete all rows where csv date is lower than 25.05.2016 23:59
  2. Save the file with a different name

我在csv的colA中有以下数据

WFQVG98765
FI Quality-Value-Growth
Some Random String 1

Datum
13-05-2016 23:59
14-05-2016 23:59
15-05-2016 23:59
16-05-2016 23:59
17-05-2016 23:59
18-05-2016 23:59
19-05-2016 02:03
.

.

.

.

这就是我现在所尝试的

^{pr2}$
            csvDate = datetime.datetime.strptime(row[0], '%d-%m-%Y %H:%M:%S') 'Error Here : ValueError: time data '' does not match format '%d-%m-%Y %H:%M:%S'

我也尝试了这个错误线

            csvDate = datetime.datetime.strptime(row[0], '%d-%m-%Y %H:%M')      'But got the same error
             if csvDate<cmpDate:
                 print (row[0]+'TRUE')

Here how can I delete the row if the condition is true and finally save it with a different name ?


Tags: csvthenamedatetimeifhereiswith
3条回答

您可以分析每一行以比较日期,并将要保留的行保存在list中。然后,您可以将这些行存储到一个新的csv文件中,如果您不再需要旧的csv文件,可以将其删除。在

这里有一个截图,可以满足您的要求:

import csv
from datetime import datetime

cmpDate = datetime.strptime('25.05.2016 23:59:00', '%d.%m.%Y %H:%M:%S')


def is_lower(date_str):
    try:
        csvDate = datetime.strptime(row[0], '%d-%m-%Y %H:%M')
        return (csvDate < cmpDate)
    except:
        pass

with open('WF.csv', 'r') as csvfile:
    csvReader = csv.reader(csvfile, delimiter=',')
    data = [row for row in csvReader if not is_lower(row[0])]

with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    [writer.writerow(row) for row in data]

is_date()给你的是假阳性。在检查日期格式时要更加严格,在将日期字符串加载到datetime时要更加严格-遵循^{}的原则之一-“应该有一种——最好只有一种——明显的方法来完成它”:

def is_date(date_string):
    try: 
        datetime.datetime.strptime(date_string, '%d-%m-%Y %H:%M:%S')
        return True
    except ValueError:
        return False

换句话说,不要混合dateutil.parser.parse()和{}。在

datetime.datetime.strptime异常表示您正在向row[0]中的函数传递一个空白字符串。在

一旦解决了这个问题,就需要添加代码将可接受的行写入新文件。在

相关问题 更多 >

    热门问题