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

问题描述 投票:0回答:1

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

My Code:

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)
python-2.7 python-dateutil
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.