我有一个从API获取的日期。它的形式是2015-01-01T15:04:23Z
。在Flask-SQLAlchemy中使用ISO时间戳
如何使用Flask-SQLAlchemy将此日期接收到模型中?
到目前为止,我已经试过了,
date = db.Column(db.DateTime)
和
date = db.Column(db.DateTime(timezone=True))
它给我的错误
StatementError: (exceptions.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input.
此外,当我使用get
找回它,我需要它以完全相同的格式。
dateutil
这个dateutil
python模块解析得很好,但是当我从表中检索它时,我需要得到2015-01-01T15:04:23Z
。
>>> from dateutil.parser import parse
>>> parse('2015-01-01T15:04:23Z')
datetime.datetime(2015, 1, 1, 15, 4, 23, tzinfo=tzutc())
“的SQLite DateTime类型只接受Python的日期时间”,它解析为Python DateTime对象日en:https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date。 –
@IljaEverilä如何在取回后以相同的格式恢复? –
有问题的格式是ISO 8601. Python对它的支持有点欠佳。有[datetime.isoformat()'](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat)用于将日期时间对象格式化为ISO 8601字符串,但会例如,不允许您使用UTC的简写“Z”(反正这不算什么大事)。在Python中所有的日期时间处理都有点痛苦,特别是如果涉及时区的话。 –