【问题标题】:Store date-time as integer in sqlite在 sqlite 中将日期时间存储为整数
【发布时间】:2026-02-11 23:15:01
【问题描述】:

当我将日期时间字符串值存储在 sqlite 表中时,我正在尝试将其转换为整数。我正在使用 Python(Flask)。我收到以下查询的“插入操作错误”。

有什么想法吗?

with sql.connect("flaskjournal.db") as con:
cur = con.cursor()
t_i = strftime('%s','time_in')
cur.execute("INSERT INTO entries (beach, board, swell, wind, score, notes, time_in) 
    VALUES (?,?,?,?,?,?,?)",(beach, board, swell, wind, score, notes, t_i))
con.commit()
msg = "Record successfully added" 

【问题讨论】:

  • 您是否尝试在 INSERT 之前打印所有变量?它们看起来都正确吗?
  • 感谢您的帮助,通过在此语句上方的 python 代码中进行转换,以不同的方式解决了这个问题。

标签: python sqlite flask


【解决方案1】:

您可以改用时间戳。

import time
from datetime import datetime

timestamp = int(time.mktime(datetime_object.timetuple())

【讨论】:

  • 谢谢...这让我想到了在 sqlite 东西之上的 python 代码中进行转换。
  • 很高兴我能帮上忙
【解决方案2】:

使t_i 通过您的创建表模式插入一个unix 时间戳。所以你不需要从 python 中处理它。

sqlite> create table t1 (
  ...> id integer primary key,
  ...> time t_i default (strftime('%s', 'now')),
  ...> txt text);

【讨论】:

  • 感谢您的帮助...使用了不同的方法,但成功了。