0

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.

4

4 回答 4

2
 datetime

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

于 2012-08-22T08:07:01.697 回答
2

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.

于 2012-08-22T08:07:34.473 回答
2

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.

于 2012-08-22T08:12:16.373 回答
1

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")
于 2012-08-22T08:13:54.080 回答