【发布时间】:2022-01-15 20:08:03
【问题描述】:
我在 JSON 文件中记录一些内容,我有一个日期时间对象,我将其转换为字符串,以便我可以将其记录在 JSON 中(它不接受日期时间对象)。
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
我的问题是如何将日期时间字符串转换回日期时间对象。我知道 strptime,只是不知道什么格式可以使它与其他 datetime.now 对象兼容。
每当我尝试使用 strptime 时,我都会使用 '(%Y, %m, %d, %H, %M, %S)' 格式并收到此错误:
ValueError: time data '2021-12-10 23:34:56.234000' does not match format '(%Y, %m, %d, %H, %M, %S)'
那么默认日期时间对象的正确格式是什么?
【问题讨论】:
-
还有子类化之类的东西:stackoverflow.com/a/12126976/42346
-
我认为你的一个非常相似的问题已经被关闭为重复。为什么不简单地使用
datetime.datetime.now().isoformat()?只需查看the docs,了解如何将日期时间对象格式化为字符串。 -
我问的问题是错误的问题,如果给您带来不便,请见谅。我不知道 .isoformat 做了什么,但从我读过的内容来看,这不只是将日期时间对象转换为字符串的一种方法吗?我正在尝试做相反的事情,我只是不知道默认格式是什么。