问题描述:

I'm using this code to get the time from lines in a file.

 for line in f:

try:

dt = parser.parse(line).replace(tzinfo=None)

print dt

except Exception, e:

print line

print(traceback.format_exc())

continue

Traceback (most recent call last):

File "./script.py", line 90, in read

dt = parser.parse(line).replace(tzinfo=None)

AttributeError: 'ArgumentParser' object has no attribute 'parse'

网友答案:

Check where you assign parser name in your code.

Compare:

>>> from argparse import ArgumentParser
>>> parser = ArgumentParser()
>>> s = 'Fri May 15 11:22:54 EDT 2015'
>>> parser.parse(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'ArgumentParser' object has no attribute 'parse'

with:

>>> from dateutil import parser
>>> parser.parse(s)
datetime.datetime(2015, 5, 15, 11, 22, 54)
网友答案:

the best thing you can do is learn to debug your issues with simple print statements

for line in f:
    try:
        dt = parser.parse(line).replace(tzinfo=None)\
        print "SUCCESS:",dt
    except Exception as e:
        traceback.print_exc()
        print "UNABLE TO PARSE: %r"%line
        continue

now you should quickly be able to find out what the problem is ... clearly the line does not look like your example

相关阅读:
Top