I am logging some stuff in a JSON file, I have a datetime object that I convert into a string so that I can log it in the JSON (it doesn't accept the datetime object).
import datetime
now = datetime.datetime()
jsonFile.dumps(now)
# Dumping datetime object as string into JSON holding my logs, I should note I'm not actually dumping the logs, I'm getting them from a different source and logging them but this is probably what the source did
print(jsonFile["time"].now)
# When I try to use .now for the datetime object, it recognizes it as a string rather than a datetime object
My question is how do I convert the datetime string back into a datetime object. I know about strptime, I just don't know what format would make it compatible with other datetime.now objects.
Any time I try to use strptime, I use the '(%Y, %m, %d, %H, %M, %S)'
format and get this error:
ValueError: time data '2021-12-10 23:34:56.234000' does not match format '(%Y, %m, %d, %H, %M, %S)'
So what is the correct format for a default datetime object?
CodePudding user response:
It would help if you have provided the format of the datetime format you saving in the json file. However let assume your date is as "YYYY-MM-DD HH:MM:SS" format. The procedure is as follows,
from datetime import datetime
dt_string = "2021-12-11 09:15:32"
# Considering date is in yyyy/mm/dd format
dt_object1 = datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
make sure you're using strptime with correct syntax.