[Python3] Read and write with datetime isoformat with json

Dictionary type data is often exchanged with json in python, but the dictionary value is retained by datetime, and when making a character string or file, `` `" YYYY-MM-DD HH-MN-SS " Make a note of how to handle it with the string ````.

datetime <-> string

It can be a string with a function called isoformat for datetime. I'll leave the separator blank.

In [1]: from datetime import datetime

In [2]: t1 = datetime.now()

In [3]: t1.isoformat()
Out[3]: '2020-05-08T22:16:39.287433'

In [4]: t1.isoformat(" ")
Out[4]: '2020-05-08 22:16:39.287433'

You can also use more strftime.

In [5]: t1.strftime("%Y/%m/%d %H:%M:%S.%f")
Out[5]: '2020/05/08 22:16:39.287433'

Conversely, use stfptime to convert a string to datetime.

In [6]: t2 = datetime.strptime("2020-01-02 20:03:12.345678", "%Y-%m-%d %H:%M:%S.%f")

In [7]: t2
Out[7]: datetime.datetime(2020, 1, 2, 20, 3, 12, 345678)

Make the dictionary a string (json)

I use json.dump and json.dumps, but at this time I can set a function to default as an argument and convert datetime to the desired string in that function. Below, from "JSON Encoder and Decoder":

If you specify> default, specify a function, and this function will be called for objects that cannot be serialized otherwise. The function must return the object in a JSON-encoded version, or throw a TypeError. If not specified, TypeError will be thrown.

It seems correct to pick up TypeError.

import json
from datetime import datetime, date

def default(o):
    if hasattr(o, "isoformat"):
        return o.isoformat()
    else:
        return str(o)

#Make a dictionary and set the current time as a value.
dict1 = {"time1": datetime.now(), "time2": datetime.now()}
print( "dict1={}".format(dict1))
print( "str(dict1)={}".format(str(dict1)) )
#Export the dictionary
s_dict1 = json.dumps(dict1, default=default)
print( "s_dict1={}".format(s_dict1) )

The execution result is as follows.

dict1={'time1': datetime.datetime(2020, 5, 8, 22, 57, 18, 564149), 'time2': datetime.datetime(2020, 5, 8, 22, 57, 18, 564163)}
str(dict1)={'time1': datetime.datetime(2020, 5, 8, 22, 57, 18, 564149), 'time2': datetime.datetime(2020, 5, 8, 22, 57, 18, 564163)}
s_dict1={"time1": "2020-05-08 22:57:18.564149", "time2": "2020-05-08 22:57:18.564163"}

It is a character string properly. In the implementation of the default function, isoformat is checked by whether it is `` hasattr```, but for example, ```is instance (o, (datetime, date)) ``` or `type (o) .__ name__ == You can also use "datetime" ``` and so on.

Dictionary from string (json)

Use json.load to read. Here customized reads can be set with object_hook.

object_hook is an optional function that is called on the result (dict) of any object literal being decoded. The return value of object_hook is used instead of dict. This feature can be used to implement your own decoders (eg JSON-RPC class hinting).

def object_hook(obj):
    new_dic = dict()
    for o in obj:
        try:
            new_dic[str(o)] = datetime.strptime(obj[o], '%Y-%m-%d %H:%M:%S.%f')
        except TypeError:
            new_dic[str(o)] = obj[o]
            pass
    return new_dic


s_dic = """{"time1": "2020-05-08 22:57:18.564149", "time2": "2020-05-08 22:57:18.564163"}"""
print( "s_dic={}".format(s_dic) )
dic = json.loads(s_dic, object_hook=object_hook)
print( "dic={}".format(dic) )

The execution result is as follows.

s_dic={"time1": "2020-05-08 22:57:18.564149", "time2": "2020-05-08 22:57:18.564163"}
dic={'time1': datetime.datetime(2020, 5, 8, 22, 57, 18, 564149), 'time2': datetime.datetime(2020, 5, 8, 22, 57, 18, 564163)}

It is properly datetime.datetime.

Other

With that, I was able to implement the desired implementation and survived the day today.

--It also shows how to implement default in a class that inherits json.JSONEncoder and specify this class in the cls argument of dumps. Which is more convenient? ――I use datetime almost all the time, but it's a bit dull to implement this every time. Is there any good way?

(2020/05/08)

Remarks

――After that, what about this? What used to be loaded in float64 is now str. I was in trouble. (2020/05/12)

Recommended Posts

[Python3] Read and write with datetime isoformat with json
Read and write JSON files in Python
Read JSON with Python and output as CSV
Read json data with python
Read and write files with Slackbot ~ Bot development with Python ~
Read json file with Python, format it, and output json
JSON encoding and decoding with python
Read and write csv files with numpy
Reading and writing JSON files with Python
[Python] Use JSON with Python
Extract "current date only" and "current date and time" with python datetime.
Read and analyze arff format dataset with python scipy.io
Parse and visualize JSON (Web application ⑤ with Python + Flask)
Read and write single precision floating point in Python
Read and write NFC tags in python using PaSoRi
datetime and file write and backup
Programming with Python and Tkinter
Read and write csv file
Encryption and decryption with Python
Read csv with python pandas
Python and hardware-Using RS232C with Python-
POST json with Python3 script
Read and write a file
About Python datetime and timezone
Let's write python with cinema4d.
Write and read a file
Write to csv with Python
python with pyenv and venv
Format json with Vim (with python)
Works with Python and R
[Python] Read the csv file and display the figure with matplotlib
[Python] Use this to read and write wav files [wavio]
Sample of HTTP GET and JSON parsing with python of pepper
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Robot running with Arduino and python
Install Python 2.7.9 and Python 3.4.x with pip.
Neural network with OpenCV 3 and Python 3
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
Write JSON Schema in Python DSL
[Python] Write to csv file with Python
Scraping with Python, Selenium and Chromedriver
Scraping with Python and Beautiful Soup
Read and use Python files from Python
[GUI with Python] PyQt5-Drag and drop-
[python] Read information with Redmine API
Reading and writing NetCDF with Python
I played with PyQt5 and Python3
Read files in parallel with Python
Python logging and dump to json
Reading and writing CSV with Python
Multiple integrals with Python and Sympy
Read fbx from python with cinema4d
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Write a batch script with Python3.5 ~
Sugoroku game and addition game with python
FM modulation and demodulation with Python
Create and read messagepacks in Python