首页 > 解决方案 > 如何将 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 数据库中未知数量的表。

我所做的调查表明了几种可能性(据我所知):

  1. 遍历import_list,并进行某种日期时间格式化,例如:
datetime.date(2011, 1, 3).strftime("%d-%m-%Y") 

这似乎不是很优雅,但如果这是我必须做的,我需要弄清楚如何做到这一点。

  1. 我已经看到了创建某种 mysql.connector.conversion.MySQLConverter 类的参考。我也不知道该怎么做,但如果这是最好的方法,我可以进一步调查。这似乎是一种很好的做事方式,因为它是在构建连接器的代码中完成的。

还是有另一种 Pythonic 方式来做我想要完成的事情?

标签: mysql-pythonmysql-connector-python

解决方案


您可以使用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

推荐阅读