Search code examples
pythondatetimepython-dateutil

What are the differences between "import dateutil.parser" and "from dateutil.parser import parse"?


Update:

I am sorry for my careless, mixing up the word parse and parser. This question should be deleted. But since someone answered it and received reputations, I kept it here. Sorry again.


What are the differences between (import dateutil.parser)

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

and (from dateutil.parser import parse)

>>> 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?


Solution

  • 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.