Python datetime.date.today() 在 sqllite3 内部没有格式化。

huangapple go评论59阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年2月6日 21:07:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定