【问题标题】:Insert datetime to database using json_populate_record使用 json_populate_record 将日期时间插入数据库
【发布时间】:2018-06-15 13:31:57
【问题描述】:

如何使用 json_populate_record 将 python 的 datetime 插入时间戳列?

我尝试了 [建议][1]。但是当我使用json_populate_record时它对我不起作用:

def add_trade(self, order_sell_id: UUID, execution_time: datetime):
    trade = {
        "order_sell_id": order_sell_id,
        "execution_time": "TIMESTAMP " + str(execution_time)
    }
    try:
        order_sql = (
            f"INSERT INTO \"trade\"(order_sell_id, execution_time) "
            f" SELECT order_sell_id, execution_time"
            f" FROM "
            f"json_populate_record(NULL::\"trade\", '{json.dumps(trade)}');")

        result = self.database.query(order_sql)
    except pg.IntegrityError as e:
        pass

对于上面的代码我有一个例外:

pg.DataError: ERROR:  invalid input syntax for type timestamp: "TIMESTAMP 2018-06-15 16:14:36"

我尝试通过添加到 dict 来插入 datetime

"execution_time": execution_time

得到:

pg.DataError: ERROR:  date/time field value out of range: "1529069127000"

【问题讨论】:

    标签: python json postgresql


    【解决方案1】:

    只使用str():

        "execution_time": str(execution_time)
    

    或者用strftime()格式化日期时间:

        "execution_time": execution_time.strftime("%Y-%m-%d %H:%M:%S")
    

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 2011-02-28
      • 1970-01-01
      • 2012-05-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多