1

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?

3
  • There's also stuff like subclassing: stackoverflow.com/a/12126976/42346 Commented Dec 11, 2021 at 15:07
  • 1
    I think a very similar question of yours has already been closed as duplicate. Why not simply use datetime.datetime.now().isoformat()? Just check out the docs on how to format datetime objects to string. Commented Dec 11, 2021 at 16:00
  • The question I was asking was the wrong question, sorry if that was inconvenient. I'm don't know what .isoformat does but from what I've read isn't it just a way to convert a datetime object into a string? I'm trying to do the opposite, I just don't know what the default formatting is. Commented Dec 11, 2021 at 17:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I just figured out the correct format, it was default, thanks anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.