0

I'm trying to determine if the current time is before or after a specified date using this code:

from datetime import datetime

def presidentvoting(self):
    electiondate = datetime.datetime(2020, 1, 31, 0, 0)
    current_time = datetime.now()
    if current_time > electiondate:
        print("You can no longer vote")

But I'm getting this error:

electiondate = datetime.datetime(2020, 1, 31, 0, 0)
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

What am I doing wrong?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

0

datetime is a module which contains a function1 that is also called datetime.

You can use it like this:

import datetime
#      ^^^^^^^^
#      the module

x = datetime.datetime(...)
#            ^^^^^^^^ the function
#   ^^^^^^^^ the module

Here datetime refers to the module, and datetime.datetime refers to the function in the module.

Or you can only import the function from the module, like this:

from datetime import datetime
#    ^^^^^^^^        ^^^^^^^^
#    the module      the function

x = datetime(...)
#   ^^^^^^^^ the function

You used a mixture of those two, which does not work:

from datetime import datetime
#    ^^^^^^^^        ^^^^^^^^
#    the module      the function

x = datetime.datetime(...)
#            ^^^^^^^^ this does not exist
#   ^^^^^^^^ the function

In case use used

import datetime
from datetime import datetime

then after the first line, datetime would refer to the module (which on its own would have been correct), but the second line would overwrite that and datetime would no longer refer to the module, but to the function.


1 Actually, datetime.datetime is a class, not a function, but for the purpose of this answer it does not matter.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65