4 ms·
The first is the datetime module. The second is a class. It comes down to how you import it. These two bits of code are equivalent: # Example 1 import dateti
by adrianh 18y ago
The first is the datetime module. The second is a class.
It comes down to how you import it. These two bits of code are equivalent:
# Example 1
import datetime; print datetime.datetime.now()
# Example 2
from datetime import datetime; print datetime.now()
I generally prefer "import FOO" over "from FOO import BAR", which is why you see example 1 used in the Django Book.
- snprbob86 18y agoThe datetime module was also written before the Python style conventions were created. If the datetime module was written today, it would make a bit more sense looking like this: import datetime datetime.DateTime.now()
- ralph 18y agoSo a `DateTime = datetime' in the module would let newer code look more conventional?
- EliAndrewC 18y agoIt would make the datetime class look more like other class names, but I'd strongly recommend against doing this. The Python community values consistency in the way that code is written (TOOWTDI) and this would be a sharp departure from that.
- snprbob86 18y agoFair, but maybe some class renames wouldn't be a bad idea for the v2 to v3 switch over. I don't know what the priorities are or what the bar is for changes that make the cut, so don't quote me on this :-)
- etal 18y agoOr it might have just been merged into the time module. The datetime module is mostly a single class which wraps the functions in the time module and adds a few convenience methods. I wouldn't be surprised if the reason for the separation is just historical -- say, time was written to match the C library, and later someone donated datetime as a set of utilities with an OO interface. Anyway, since the common utilities in that are all attached to the datetime class in that module, there's no harm in importing the class directly. You could even fix the naming yourself, if you were so inclined: from datetime import datetime as DateTime DateTime.now()