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?

rabbibillclinton
  • 410
  • 4
  • 17
  • There's also stuff like subclassing: https://stackoverflow.com/a/12126976/42346 – mechanical_meat Dec 11 '21 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](https://docs.python.org/3/library/datetime.html) on how to format datetime objects to string. – FObersteiner Dec 11 '21 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. – rabbibillclinton Dec 11 '21 at 17:27

1 Answers1

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.

SKR123
  • 233
  • 1
  • 12