Home > Blockchain >  python importing datetime module question
python importing datetime module question

Time:07-21

I have noticed while reading up on python datetime module there are times when responses will show

from datetime import datetime (or date or time)

and I'm not sure why I should or would do this. What is the rational behind this or could someone point me to some resources that might explain this?

CodePudding user response:

The datetime module defines a bunch of different classes. If you just use

import datetime

Then you have to write things like datetime.datetime.strptime() -- the first datetime is the module name, the second is the class name. By using the from syntax you can shorten this to just datetime.strptime().

CodePudding user response:

The datetime module has multiple classes inside of it. Though at first the name may seem confusing, when you compare it to another module, like random, it starts to make more sense.

If we are only going to use randint from the random module, we don't want to import the whole random module so we will do something like this: from random import randint

It's the same concept with datetime except the only part of datetime that we want is the datetime class. Inside of the module datetime there is a datetime class, just how in the module random there is a randint function.

If you wanted to import the whole random module then use randint you would do:

import random
random_number = random.randint(0, 5)

Just as if you wanted to import the whole datetime module, then use the datetime class you'd do:

import datetime
now = datetime.datetime.now()

CodePudding user response:

The first datetime refers to the module, whereas the second is a type defined therein. Depending on the application you can choose to import datetime.datetime, datetime.date or datetime.time.

More information can be found at the link

  • Related