Home > front end >  Why is my datetime object being converted to a string?
Why is my datetime object being converted to a string?

Time:10-25

I have a class with a public attribute created_at, that will stored the date of a current time, but when I check what type of object it is i says it is a string:

def __init__(self, *args, **kwargs):
    """Instantiation Method"""
    if not kwargs:
        self.id = uuid4()
        self.created_at = datetime.now().isoformat()
        self.updated_at = datetime.now().isoformat()

When I check what type of object it i I get the following:

t = Model()
print(type(t.created_at))

Output:

<class 'str'>

It should be a datetime object but it says it is a string, is it because of the isoformat() ?

CodePudding user response:

Calling isoformat() return string.

https://docs.python.org/3/library/datetime.html#datetime.date.isoformat

CodePudding user response:

The problem is .isoformat() that convert the date to str:

class Model():
    def __init__(self, *args, **kwargs):
        """Instantiation Method"""
        if not kwargs:
            self.created_at = datetime.utcnow()
        
t = Model()
print(type(t.created_at))

Output:

<class 'datetime.datetime'>
  • Related