Search code examples
pythonpython-3.xpython-importpython-datetime

Why cant I use this reference after importing the datetime class?


I am trying to import timedelta from class datetime without importing everything (import datetime):

from datetime import datetime, timedelta

datetime.timedelta(seconds=1)

Error: Unresolved attribute reference 'timedelta' for class 'datetime'


Solution

  • Looking at your import statement

    from datetime import datetime, timedelta
    

    You imported two things from the module datetime. The datetime and timedelta classes, which are now injected into the applications global scope. You no longer need to use the datetime module name to reference those classes.

    You can just call it like.

    >>>timedelta(seconds=1)
    

    If you imported the module as whole (which I realise you don't want to do) then you could use the syntax from your question.

    >>> import datetime
    >>> datetime.timedelta(seconds=1)
    datetime.timedelta(0, 1)