equanimity equanimity - 1 month ago 7
Python Question

Error when converting string to date object from command line in Python

When I run the following code, I don't see any problems:

as_of_date = '10-16-17'
today = datetime.datetime.strptime(as_of_date, '%m-%d-%y').date()
type(today)
print(today)

Out: datetime.date
Out: 2017-10-16


However, when I run a script named
GetStats.py
that takes several arguments from the command line, I get an error.

The command line consists of 5 arguments and looks as follows:

python GetStats.py Client_A.cfg 30 -d 10-16-17


The last argument ("10-16-17") on the command line represents a date.

The code in the GetStats.py script is as follows:

import sys
from datetime import datetime, timedelta, time, date

as_of_date = sys.argv[4]
today = datetime.datetime.strptime(as_of_date, '%m-%d-%y').date()

print (today)


The code doesn't hit the print statement and instead shows the following error:

type 'exceptions.AttributeError'


Does anyone see the mistake when I try to pass that date from the command line?

Thanks!

Answer

The problem is with your import:

from datetime import datetime and then you try to call datatime.datetime.strptime

By doing this, you're trying to call the function datetime.datetime.datetime.strptime which doesn't exist.

Therefore, to fix this change datetime.datetime to simply datetime in your code.

Comments