Hi
I have several case with different results:
Could someone explain me why it gives an error or not. It seems that the order of the import plays a role.
Thanks
V
import datetime
from datetime import datetime
dt=datetime.datetime.strptime(input("Input date (dd-mm-jjjj): "),"%d-%m-%Y")
=> AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
same as above but different order:
from datetime import datetime
import datetime
dt=datetime.datetime.strptime(input("Input date (dd-mm-jjjj): "),"%d-%m-%Y")
=> no error
from datetime import datetime
import datetime
dt=datetime.strptime(input("Input date (dd-mm-jjjj): "),"%d-%m-%Y")
=> AttributeError: type object 'datetime.datetime' has no attribute 'strptime'
import datetime
from datetime import datetime
dt=datetime.strptime(input("Input date (dd-mm-jjjj): "),"%d-%m-%Y")
=> no error
Tuhin PaulPosted Mar 20, 2023, 12:06 AM
In the third example, the datetime module is being imported first, and then the datetime class is imported from it. However, the strptime method is a class method of the datetime class, not the datetime module. The correct way to import and use it is:
Tuhin PaulPosted Mar 20, 2023, 12:06 AM
I think the reason for the error in the first and third examples is due to the way the import statements are written.
In the first example, both the module name and the class name are being imported using the same name (datetime). This creates a conflict when trying to access the datetime class inside the datetime module.
import datetime
dt = datetime.datetime.strptime(input("Input date (dd-mm-jjjj): "),"%d-%m-%Y")