Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "import datetime" and "from datetime import datetime", which datetime to use

// Works and output is 2017-03-13 14:14:45.157593; then I can drill down to minute level, etc.

from datetime import datetime
print(datetime.today())

// Works and output is 2017-03-13

import datetime
print(datetime.date.today())

// Both together It doesn't work. Outputs error: AttributeError: module 'datetime' has no attribute 'today'

from datetime import datetime
import datetime
print(datetime.today())
print(datetime.date.today())
  1. Why there are two different modules?
  2. Why I can't use them together? I don't want to use them together but need to understand, how the python interpreter is working (as it executes single statement at a time)... does it sees the first import and ignore the second import while executing the first statement or something else?

Thanks, David

like image 850
David Avatar asked Jan 31 '26 10:01

David


1 Answers

There is only one module: datetime, which contains a class datetime.

If you do import datetime then datetime is the module and datetime.datetime is the class.

If you do from datetime import datetime then datetime is the class and you don't have a name for the module.

If you do both, then datetime is the last one executed, since the name datetime is reassigned by the additional import statement.

This confusion is why PEP 8 suggests different casing for module names and class names (the class should be named DateTime according to PEP 8) but datetime was in the standard library well before PEP 8 was written.

like image 186
kindall Avatar answered Feb 02 '26 23:02

kindall