shantanuo
shantanuo

Reputation: 32276

importing required module

The following code is working as expected. But I have 2 questions.

# import datetime # does not work
from datetime import datetime
row = ('2002-01-02 00:00:00.3453', 'a')
x = datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S.%f")

1) Why does only import datetime does not work?

2) How do I know to which module does the 'strptime' method belogs to?

>>> help('modules strptime') 

does not provide the info I am looking for.

Upvotes: 0

Views: 63

Answers (4)

schacki
schacki

Reputation: 9533

Either you do:

import datetime
x = datetime.datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S.%f")

or you do:

from datetime import datetime
x = datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S.%f")

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174708

The method is datetime.datetime.strptime, and when you do a simple import datetime, you are only importing the top level module, not the datetime class

You can test this out like this:

>>> import datetime
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'dat
etime': <module 'datetime' (built-in)>, '__doc__': None, '__package__': None}


>>> from datetime import datetime
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'dat
etime': <type 'datetime.datetime'>, '__doc__': None, '__package__': None}

You can see that there are two different objects in your namespace.

For your second question Python's built-in help() only works for those modules and objects that are loaded. If you didn't import datetime, help() can't help you. So its best to browse the documentation for this; and a google on python strptime generally lands you at the correct documentation page.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799390

1) It works fine. But the datetime class within is separate. You need to refer to it as datetime.datetime.

2) Use the General Index. But methods belong to objects, not modules.

Upvotes: 2

Aesthete
Aesthete

Reputation: 18858

 datetime

Is a module. It also has a member named datetime which has a method named strptime

Upvotes: 2

Related Questions