Python - 如果没有日期模式,请跳过

时间:2014-05-30 21:20:04

标签: python date csv pattern-matching

我有一个csv,例如我:

Date,Comment

2014-05-29,Last time we will see

What about next time?"

2014-05-29,"""still want to be seen as the good guys..."""

This is my world. 

2014-05-29,And so the game begins... ;)

2014-05-29,"Btw, this is... 

我想跳过第一列中没有日期格式的行。我有这个:

a = []
csvReader = csv.reader(open(csv_file_to_open, 'rb'), delimiter=',')
for row in csvReader:
    a.append(row)

for row in a:
    if row[0] == "date format then": <= here I need some pattern filter but I don't know how to do it
        print 'yes'

日期始终采用%Y-%m-%d格式。

1 个答案:

答案 0 :(得分:2)

您可以使用datetime模块检查:

import datetime
a = []
csvReader = csv.reader(open(csv_file_to_open, 'rb'), delimiter=',')
for row in csvReader:
    a.append(row)

for row in a:
    try:
        datetime.datetime.strptime(row[0],'%Y-%m-%d')
        print 'yes'
    except ValueError:
        continue

应该这样做!