从 python 中的 SQL 查询中选择时间戳


cur.execute('Select ts from testtable where nd_a>%s and nd_b>%s and nd_c>%s',(medA,medB,medC))
result_ts=cur.fetchall()
print (result_ts)

当我得到输出时,它看起来像这样:

((datetime.datetime(2020, 1, 1, 1, 15, 24),), (datetime.datetime(2020, 1, 1, 1, 15, 38),), (datetime.datetime(2020, 1, 1, 1, 16, 30),), (datetime.datetime(2020, 1, 1, 1, 16, 37),), (datetime.datetime(2020, 1, 1, 1, 17, 8),), (datetime.datetime(2020, 1, 1, 1, 17, 14),))

当我需要这种格式的输出日期时:YYYY-MM-DD HH:MM:SS

如何将其更改为此格式视图?

你可以做这样的事情:

cur.execute('Select ts from testtable where nd_a>%s and nd_b>%s and nd_c>%s',(medA,medB,medC))
result_ts=cur.fetchall()
for result in result_ts:
print(result[0])

这将打印:

2020-01-01 01:15:24
2020-01-01 01:15:38
2020-01-01 01:16:30
2020-01-01 01:16:37
2020-01-01 01:17:08
2020-01-01 01:17:14

如果你想要一个字符串时间戳,你应该使用strftime方法。

cur.execute('Select ts from testtable where nd_a>%s and nd_b>%s and nd_c>%s',(medA,medB,medC))
result_ts=cur.fetchall()
timestamps = []
for r in results_ts:
timestamps.append(r[0].strftime('%Y-%m-%d %H:%M:%s'))

这将为您提供转换为时间戳字符串的结果列表:)

最新更新