import datetime vs from datetime import datetime

1,893 views
Skip to first unread message

niknok

unread,
Apr 9, 2011, 6:37:15 PM4/9/11
to web...@googlegroups.com
Hello.

What is the difference between the statements: import datetime vs from datetime import datetime

I got stuck with my IS_DATE_IN_RANGE error "<type 'exceptions.AttributeError'>(type object 'datetime.datetime' has no attribute 'timedelta')" until i added "import datetime" to the controller. All the while, I thought I already loaded datetime because I already have this line: "from datetime import datetime".

TIA.

/r
Nik

Anthony

unread,
Apr 9, 2011, 7:27:43 PM4/9/11
to web...@googlegroups.com
The different methods of importing result in different namespaces -- see http://effbot.org/zone/import-confusion.htm.
 
The datetime module is probably particularly confusing because the module also includes a datetime class, so datetime.datetime refers to the datetime class within the datetime module. If you do 'from datetime import datetime', you're only importing the datetime class, so when you refer to 'datetime' in your code, it's referring to the datetime class, not the whole datetime module. That means 'datetime.timedelta' won't work, because it's expecting 'timedelta' to be an attribute of the datetime class, when it's actually a class within the datetime module. If you want to use from-import to access the timedelta class, you can do 'from datetime import timedelta', and then you can refer to 'timedelta' directly.
 
Anthony

niknok

unread,
Apr 10, 2011, 5:48:38 PM4/10/11
to web2py-users
Thank you Anthony. That is very clear now.

On Apr 10, 7:27 am, Anthony <abasta...@gmail.com> wrote:
> On Saturday, April 9, 2011 6:37:15 PM UTC-4, niknok wrote:
>
> > Hello.
>
> > What is the difference between the statements: import datetime vs from
> > datetime import datetime
>
> > I got stuck with my IS_DATE_IN_RANGE error "<type
> > 'exceptions.AttributeError'>(type object 'datetime.datetime' has no
> > attribute 'timedelta')" until i added "import datetime" to the controller.
> > All the while, I thought I already loaded datetime because I already have
> > this line: "from datetime import datetime".
>
> The different methods of importing result in different namespaces -- seehttp://effbot.org/zone/import-confusion.htm.
Reply all
Reply to author
Forward
0 new messages