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



我有一个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

你可以使用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

这个应该可以!

最新更新