Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import datetime versus from datetime import datetime

I trying to set a datetime with timezone information. In this case UTC.

when I try this code, it works:

from datetime import datetime, timezone
prueba = timezone.utc

fecha = datetime(1900, 1, 1, 1, 00, 00, 00000, tzinfo=prueba)

but when I try this one, it faults with a "TypeError: 'module' object is not callable"

import datetime
prueba = datetime.timezone.utc

fecha = datetime(1900, 1, 1, 1, 00, 00, 00000, tzinfo=prueba)

It doesn't make sense to me because I'm referring to the same class I suppose.

like image 445
Chemado Avatar asked Aug 31 '26 10:08

Chemado


1 Answers

The difference is that the datetime module includes a datetime class. When you do:

from datetime import datetime, timezone

You are importing the datetime.datetime class, and calling it datetime and the datetime.timezone class, and calling it timezone.

When you do

import datetime

what you are doing is importing the whole datetime module.datetime now refers to the datetime module, not the datetime.datetime class. The datetime class needs to be called as datetime.datetime().

like image 178
CDJB Avatar answered Sep 02 '26 10:09

CDJB