sparkandshine sparkandshine - 8 days ago 6
Python Question

Why doesn't "dateutil.parser.parser" return "datetime.datetime"?

According to the descriptions of

, but it returns a
datetime.datetime
object, it returns
dateutil.parser.parser
in the following case.

>>> import dateutil.parser
>>> t = dateutil.parser.parser("2012-01-19 17:21:00 BRST")
>>> type(t)
<class 'dateutil.parser.parser'>


parser
does return a
datetime.datetime
object.

>>> from dateutil.parser import parse
>>> t = parse("2012-01-19 17:21:00 BRST")
>>> type(t)
<type 'datetime.datetime'>


Can anyone explain the differences between
import dateutil.parser
and
from dateutil.parser import parse
?

Answer

The problem is that you are actually calling the constructor for the parser object, not the parse method. You can either call dateutil.parser.parse or instantiate a dateutil.parser.parser object and call its parse() method.

>>> import dateutil.parser
>>> t = dateutil.parser.parse("2012-01-19 17:21:00 BRST")
>>> type(t)
datetime.datetime
>>> t
datetime.datetime(2012, 1, 19, 17, 21)

Generally you can construct a parser object with a dateutil.parser.parserinfo object, but since you're not actually using the parser object, it's not throwing an error when it detects that you've passed it a string instead.

Comments