英文:
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 today's 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.
*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()
英文:
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.
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()
答案1
得分: 0
不应在客户端创建用户时包含日期字段。在Django中,通过定义DateField并注册每个用户,可以自动将该字段保存在数据库中。
您还可以使用以下代码片段记录用户的创建日期以及用户更新其个人资料的日期。
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论