0

I want to save datetime.now() to a json file where I can then later open the json file and convert that back to a json file. Is there a built in function for something like this? so heres what I think

import json
from datetime import datetime
data = {}
data['posted-time'] = datetime.now()
with open(file, 'w') as f:
    json.dump(data, f)

If I were to load back in that json with json.load(f) would it still be a date time object and if not, how do I make it one?

2 Answers2

0

You might have to use date time encoder and decoder for the same. please refer below code

from datetime import datetime
import json
from json import JSONDecoder
from json import JSONEncoder

obj = {'name':'foo', 'type': 'bar','date':datetime.now()}


class DateTimeDecoder(json.JSONDecoder):

    def __init__(self, *args, **kargs):
        JSONDecoder.__init__(self, object_hook=self.dict_to_object,
                             *args, **kargs)
    
    def dict_to_object(self, d): 
        if '__type__' not in d:
            return d

        type = d.pop('__type__')
        try:
            dateobj = datetime(**d)
            return dateobj
        except:
            d['__type__'] = type
            return d

class DateTimeEncoder(JSONEncoder):
    """ Instead of letting the default encoder convert datetime to string,
        convert datetime objects into a dict, which can be decoded by the
        DateTimeDecoder
    """
        
    def default(self, obj):
        if isinstance(obj, datetime):
            return {
                '__type__' : 'datetime',
                'year' : obj.year,
                'month' : obj.month,
                'day' : obj.day,
                'hour' : obj.hour,
                'minute' : obj.minute,
                'second' : obj.second,
                'microsecond' : obj.microsecond,
            }   
        else:
            return JSONEncoder.default(self, obj)

            
j = json.loads(json.dumps(obj,cls=DateTimeEncoder), cls=DateTimeDecoder)
print(j['date'])
print(type(j['date']))

Ref : Link

Akash senta
  • 483
  • 7
  • 16
0

If you insist on using JSON then following can be a solution for you:
Snippet to dump the data:

import json
from datetime import datetime
data = {}
data['posted-time'] = str(datetime.now())
with open("test.json", 'w') as f:
    json.dump(data, f)

Snippet to load the data as a datetime object

with open("test.json", "r") as f:
    d = json.load(f)
time = datetime.strptime(d["posted-time"], "%Y-%m-%d %H:%M:%S.%f")

In case you want to use custom format for date and time you would need to use strftime while dumping the data.
Another way around this can be to use pickle:

import pickle
time_d = {
    "posted_time": datetime.now()
}
with open("file.dat", 'wb') as f:
    pickle.dump(time_d, f)
with open("file.dat", "rb") as f:
    data = pickle.load(f)
print(type(data["posted_time"]))

This will output:
<class 'datetime.datetime'>

Amartya Gaur
  • 665
  • 6
  • 21