【问题标题】:how to convert python time.time() to date format for sql insertion如何将 python time.time() 转换为日期格式以进行 sql 插入
【发布时间】:2021-04-05 07:16:06
【问题描述】:

我有以下脚本:

import time
start = time.time()
end = time.time()
runtime = end - start

我正在尝试将开始、结束和运行时变量插入到数据库表中。我目前正在获得

cx_Oracle.DatabaseError: ORA-00932: inconsistent datatypes: expected DATE got NUMBER

这是因为 start 和 end 是整数,我需要它们是日期格式。

我的尝试是这样转换:

start.strftime('%Y-%m-%d %H:%M:%S')

但这不起作用。我想使用变量 start 和 end 并使用 time 模块将它们转换为适当的格式。

【问题讨论】:

  • 请指定您使用的sql连接器。

标签: python sql date cx-oracle


【解决方案1】:

尝试改用datetime

from datetime import datetime

start = datetime.now() # Type: datetime.datetime
end = datetime.now() # Type: datetime.datetime
runtime = end - start
runtime.total_seconds() # Type: float

编辑:使用time 模块:

import time
start = time.time()
end = time.time()
start_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start))
end_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end))

如果你更喜欢time.struct_time,那么你可以添加

start_as_struct = time.strptime(start_as_str , '%Y-%m-%d %H:%M:%S')
end_as_struct = time.strptime(end_as_str , '%Y-%m-%d %H:%M:%S')

但是,如果你想要它作为日期时间,那么你将需要使用第一个模块

【讨论】:

  • "使用时间模块。"
  • @syrkull 答案已更新,如果这是您要找的,请告诉我
猜你喜欢
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 2014-02-25
相关资源
最近更新 更多