pymysql对 datetime的处理

3130阅读 0评论2021-10-28 大镇
分类:Python/Ruby


使用pymysql查询数据库数据,由于数据库表的字段里有datatime类型字段,返回的结果形式如下:
datetime.datetime(2019, 3, 19, 10, 6, 6)

那么我们对结果进行json.dumps时,会报错:
TypeError: Object of type datetime is not JSON serializable

此时有三种处理方案

一、重写json函数
  1. import datetime
  2. import json
  3.  
  4. class DateEncoder(json.JSONEncoder):
  5.     def default(self, obj):
  6.         if isinstance(obj,datetime.datetime):
  7.             return obj.strftime("%Y-%m-%d %H:%M:%S")
  8.         else:
  9.             return json.JSONEncoder.default(self,obj)
  10.  
  11. dic={'name':'jack', 'create_time': datetime.datetime(2019, 3, 19, 10, 6, 6)}
  12.  
  13. print(json.dumps(dic,cls=DateEncoder))
此方法来自:
  1. https://blog.csdn.net/t8116189520/article/details/88657533
二、遍历返回数据,如果是 datetime 则转化为字符串

  1. # 先获取执行结果
  2. data = db_cursor.fetchall()

  3. log.info("### Formatting SQL results ###")
  4. x = 1
  5. for list in data:
  6.     y = 1
  7.     for value in list:
  8.         key = "row" + "-" + str(x) + "-" + str(y)
  9.         # 如果返回值是 datetime.datetime 格式,则将其转换成str,否则 json.dumps会报错
  10.         if isinstance(value, datetime.datetime):
  11.             value = value.strftime('%Y-%m-%d %H:%M:%S')
  12.         execute_case[key] = value
  13.         y = y+1
  14.     x = x+1
  15. execute_case = json.dumps(execute_case, ensure_ascii=False)
核心代码是
  1. if isinstance(value, datetime.datetime):
  2.    value = value.strftime('%Y-%m-%d %H:%M:%S')

三、从MySQL下手,让MySQL返回string的数据类型
MySQL做数据类型转换的函数是CAST。于是将SQL语句变成:

  1. SELECT country, CAST(date AS CHAR) AS date from mytable

  2. 此方案来自
  3. https://www.cnblogs.com/oDoraemon/p/7019163.html

上一篇:python selenium鼠标键盘操作(ActionChains)
下一篇:python requests发送POST请求带文件和json