如何使用tzlocal()将datetime保存到MariaDB中?

2024-10-03 06:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自Postgres的背景,是MariaDB(MySQL)的新手。你知道吗

当我试图将DateTime保存到MariaDB中时,我遇到了这个错误。你知道吗

sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1292, "Incorrect datetime value: '2017-11-25 16:33:26+00:00' for column 'expires_at' at row 1") [SQL: 'INSERT INTO user (username, password, created_at, expires_at, expires_at_ms) VALUES (%s, %s, %s, %s, %s)'] [parameters: ('uuid1', '...', FakeDatetime(2017, 10, 25, 0, 0), FakeDatetime(2017, 11, 25, 16, 33, 26, tzinfo=tzlocal()), 0)]

根据文档,如果我使用TIMESTAMP字段而不是DateTime,我应该绕开它。但这也没用。你知道吗

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)

问题是这个日期'2017-11-25 16:33:26+00:00',它是这样呈现的:FakeDatetime(2017, 11, 25, 16, 33, 26, tzinfo=tzlocal())

伪数据来自Python中的@freeze_time("2017-10-25"),在这种情况下应该无关紧要。你知道吗

SqlAlchemy中的模型:

class User(db.Model):
    __tablename__ = 'user'

    username = db.Column(db.String(36), primary_key=True)
    password = db.Column(db.String(100))
    created_at = db.Column(db.TIMESTAMP())
    expires_at = db.Column(db.TIMESTAMP())
    expires_at_ms = db.Column(db.BigInteger())

进一步分析:

from dateutil import parser as dt_parser
expires_at = dt_parser.parse('Sat, 25 Nov 2017 16:33:26 GMT')

这失败了,因为MySQL不喜欢tzinfo。 datetime.datetime(2017, 11, 25, 16, 33, 26, tzinfo=tzlocal())

但是expires_at = datetime.datetime.now()是有效的。因为这对于MySQL是可以接受的:datetime.datetime(2017, 12, 2, 9, 44, 55, 392927)


Tags: fromparserfordbdatetimetimemysqlcolumn