mysql-python - 如何将 mysql 连接器 SELECT 结果“datetime.date(2019, 3, 11)”转换为 '11/03/2019'
问题描述
使用 Python 3.7.3 和 mysql-connector 8.0.18,我的 SELECT 结果如下所示:
[['2019-001', datetime.date(2019, 3, 11), 'Services']]
我希望结果如下所示:
[['2019-001', '11/03/2019', 'Services']]
代码片段:
...
table = 'Customer'
select = "SELECT * FROM %s"
cursor.execute(select % table)
for row in cursor:
append_list = list(row)
import_list.append(append_list)
print(import_list) #import_list is actually a list of lists
...
我无法修改 SELECT 语句(使用 ... DATE_FORMAT(Date, '%d/%m/%Y')),因为我不知道何时/是否会遇到 DATE 字段,或者字段,因为我正在迭代 MySQL 数据库中未知数量的表。
我所做的调查表明了几种可能性(据我所知):
- 遍历import_list,并进行某种日期时间格式化,例如:
datetime.date(2011, 1, 3).strftime("%d-%m-%Y")
这似乎不是很优雅,但如果这是我必须做的,我需要弄清楚如何做到这一点。
- 我已经看到了创建某种 mysql.connector.conversion.MySQLConverter 类的参考。我也不知道该怎么做,但如果这是最好的方法,我可以进一步调查。这似乎是一种很好的做事方式,因为它是在构建连接器的代码中完成的。
还是有另一种 Pythonic 方式来做我想要完成的事情?
解决方案
您可以使用strftime("%Y/%m/%d")
格式化时间戳。例如:
cursor.execute(select % table)
result = cursor.fetchall()
print(result[0][1].strftime("%Y/%m/%d")) # should give you the timestamp in the format you desire
推荐阅读
- javascript - 如何在html元素中显示javascript原型、构造函数、范围
- r - 一个 R 元编程问题:公式和建模函数的关心和输入
- powershell - powershell 写入 0xC3BF (UTF-8) 而不是 0xff
- php - Mac上的Xampp:PHP intl安装错误:找不到'unicode/ubrk.h'文件'错误:`make'失败
- json - 使用 asp net core mvc 的 docker 的 AWS S3 问题
- apache - 如何在 apache2 中将 ErrorDocument 与 VirtualDocumentRoot 一起设置?
- sql - 在 PostgreSQL 中,计算一个 ID 出现在单个 Date 列中的平均持续时间(时间间隔)
- python - 在传递给函数调用时发布增量值
- javascript - React js,对 CSS 文件感到困惑
- javascript - React-three-fiber 如何从另一个组件触发 GLTF 动画