Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python datetime.date.today() not formatting inside sqllite3

In my database query which is executed with the sqlite3 module I insert a new row of data which includes a date field.

The problem is when getting todays date with datetime.date.today().strftime('%Y-%m-%d') which outputs '2023-02-06' (expected output), it changes inside the database to '2015'. Why does this happen?

This is a Django project so that is where i created the model for the database.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

models.py

class User(models.Model):
    ...
    date_joined = models.DateField('%Y-%m-%d')
    ...

database.py

def add_user(self, email, password):
    date = datetime.date.today().strftime('%Y-%m-%d')
    self.cursor.execute(f"""
        INSERT INTO App_user ('username','email','password', 'email_preference', 'region', 'date_joined')
        VALUES ('{username}', '{email}', '{password}', 'All', 'None', {date})
    """)
    self.con.commit()

>Solution :

You should not have the date field on the client side when you create the user. This field in Django is automatically saved in the database by defining DateField and registering every user.
You can also use the following code snippet to record the user’s creation date as well as the date the user updated his profile.

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading