from .. import or just import datetime

I’m using

from datetime import datetime

Somethings don’t work and they work only if I replace the above with import datetime

I understand that with using from we need to write datetime.now() and in using just import we need to write as datetime.datetime.now() - but there are other functions as well like datetime.strptime and very often I get errors like AttributeError: module 'datetime' has no attribute 'foo'.

So what’s the convention ?

The convention is whatever you want it to be. A quick scan of the Django source code shows a reasonably even split between the two forms.

If I only need one or two classes from the datetime module in a particular source code file, then I find the from datetime import ... form to be easier to read in the rest of the code.

(Side note: In a couple of cases where I’m doing a lot of date-related work involving most of the classes from that module, I have used the form import datetime as dtm to make it explicit when I’m referring to the module as opposed to the class.)