Python2.7 json conversion date processing example, python2.7json

Source: Internet
Author: User

Python2.7 json conversion date processing example, python2.7json

Python2.7 integrates the json processing (simplejson), but in actual applications, the data queried from mysql usually has a date format. At this time, an error is reported:

TypeError: datetime. datetime (2007, 7, 23, 12, 24, 25) is not JSON serializable

It indicates that there was a problem with the date conversion, and then the solution was found online.

Import jsonfrom datetime import date, datetimedef _ default (obj): if isinstance (obj, datetime): return obj. strftime ('% Y-% m-% dT % H: % M: % s') elif isinstance (obj, date): return obj. strftime ('% Y-% m-% D') else: raise TypeError (' % r is not JSON serializable '% obj) print json. dumps ({'D': datetime. now (), 'today': date. today (), 'x': 111}, default = __default)

The following method is used to serialize a mysql dataset.

Conn?self.getconnection({{cursor=conn.cursor({{cursor.exe cute (sqlText, params); result = cursor. fetchall () jsonstr = json. dumps (myresult, default =__ default) print jsonstr

The key point is to overwrite the default method.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.