使用dateutil在python中识别字符串中的日期,不返回任何输出

时间:2018-03-01 07:02:31

标签: python-2.7 python-dateutil

我正在尝试从包含文本条目的列中标识日期,并将日期输出到文本文件。但是,我的代码没有返回任何输出。我似乎无法弄清楚我在代码中做错了什么。我很感激你的帮助。

我的代码:

import csv

from dateutil.parser import parse

with open('file1.txt', 'r') as f_input, open('file2.txt', 'w') as f_output:

     csv_input = csv.reader(f_input)

     csv_output = csv.writer(f_output)

     for row in csv_input:
         x = str(row[3])

         def is_date(x):
             try:
                parse(x)
                csv_output.writerow([row[0], row[1], row[2], row[3], row[4]])
             # no return value in case of success 
             except ValueError:
                return False 

         is_date(x)

1 个答案:

答案 0 :(得分:2)

猜你有点输入,例如:

1,2,3, This is me on march first of 2018 at 2:15 PM, 2015
3,4,5, She was born at 12pm on 9/11/1980, 2015

您想要的版本

from dateutil.parser import parse

with open("input.txt", 'r') as inFilePntr, open("output.txt", 'w') as outFilePntr:
    for line in inFilePntr:
        clmns = line.split(',')
        clmns[3] = parse( clmns[3], fuzzy_with_tokens=True )[0].strftime("%Y-%m-%d %H:%M:%S")
        outFilePntr.write( ', '.join(clmns) )

注意,由于您没有触及其他列,我只是将它们保留为文本。因此,不需要csv。你从未对parse的返回值做任何事情。我使用模糊标记,因为我的第三列有一些隐藏在其他文本中的日期。返回的datetime对象将转换为我喜欢的字符串(see here)并插入第三列,替换旧值。 我再次用逗号分隔重新组合字符串,将其写入output.txt,看起来像:

1, 2, 3, 2018-03-01 14:15:00,  2015
3, 4, 5, 1980-09-11 12:00:00,  2015