Compare a datetime string with a datetime instance Python

Viewed 35

I am trying to compare a string with a datetime in it and a datatime instance

if datetime.fromisoformat(item[1]) < datetime.datetime.utcnow():

with "item[1]" being str("2021-07-02 23:09:09.936720") but it always raises the error:

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

I can't find a way to fix this error since I don't see the exact problem, thanks a lot if you could help :)

1 Answers

The obvious problem is in the second part of the if-statement.

datetime.datetime.utcnow()

The utcnow() method call should be written as datetime.utcnow()

I tried it on my local machine and this is the code that worked for me:

from datetime import *
var = "2021-07-05 23:09:09.936720"

if datetime.fromisoformat(var) < datetime.utcnow():
    print("Less!")
else:
    print("Not less!")

NOTE: Important part is to import the module using "from datetime import *", otherwise the fromisoformat() method wouldn't be imported.

Related