34 lines
756 B
Python
34 lines
756 B
Python
import datetime
|
|
import json
|
|
|
|
|
|
class DatetimeEncoder(json.JSONEncoder):
|
|
def default(self, obj):
|
|
if isinstance(obj, (datetime.date, datetime.datetime)):
|
|
return obj.isoformat()
|
|
|
|
|
|
def print_and_return(obj):
|
|
for k, v in obj.items():
|
|
if not isinstance(v, str):
|
|
continue
|
|
try:
|
|
dt = datetime.datetime.fromisoformat(v)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
dt = datetime.date.fromisoformat(v)
|
|
except Exception:
|
|
pass
|
|
obj[k] = dt
|
|
return obj
|
|
|
|
|
|
d = dict(user=dict(joined=datetime.datetime.now()), other_user=datetime.date.today())
|
|
|
|
s = json.dumps(d, cls=DatetimeEncoder)
|
|
print(s)
|
|
print()
|
|
|
|
print(json.loads(s, object_hook=print_and_return))
|