简体   繁体   中英

How to overcome TypeError: Object of type datetime is not JSON serializable

PreFile:

  PreFile = {
         "Preferences": {
                "Quotas": {
                          "Rate limit": 0,
                          "Reset time": "2020-10-28 10:57:21.482911"
                           }
            }
     }

My code:

    PrefFile["Preferences"]["Quotas"]["Reset time"] = data_option
       with open(Preferences_Path, 'w') as Preferences_File:
           json.dump(PrefFile, Preferences_File, indent=4, sort_keys=True)

 
    PreResetTime = PreFile["Preferences"]["Quotas"]["Reset time"]
    ResetTime = datetime.strptime(PreResetTime, '%Y-%m-%d %H:%M:%S.%f')

Error output: TypeError: Object of type datetime is not JSON serializable

  File "main_functions.py", line 158, in updating_preferences
    json.dump(PrefFile, Preferences_File, indent=4, sort_keys=True)

I'm going to use ResetTime later in the program

if(ResetTime < (time_now - timedelta(hours=24))):
      code...

What can I do to overcome this error? Thanks to everyone!

For this line:

PrefFile["Preferences"]["Quotas"]["Reset time"] = data_option

Change to this or similar:

PrefFile["Preferences"]["Quotas"]["Reset time"] = data_option.isoformat()

https://docs.python.org/library/datetime.html#datetime.datetime.isoformat

convert your data_option to string before updating PrefFile["Preferences"]["Quotas"]["Reset time"] Answer by @Shijith

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM