[英]Python replace the default __str__ implementation of datetime?
Is it a way to replace/customize the default __str__
of datetime?这是一种替换/自定义 datetime 的默认__str__
的方法吗?
from datetime import datetime
x = datetime.now() # x can be any date from parameters
print(x) # str(x) returns 2020-10-07 10:38:08.048291 too, but I want a different format
I need to change the default __str__
behave for other functions like json.dump(x, default=str)
.我需要更改其他函数的默认__str__
行为,例如json.dump(x, default=str)
。
x = 12, 'abc', datetime.now(), 223, ....
json.dump(x, default=str)
I think next is a cleaner un-intrusive approach for your case rather than modifying datetime
class's __str__
method.我认为接下来是针对您的情况的更清洁的非侵入式方法,而不是修改datetime
类的__str__
方法。 You provide custom convertors for any types you need like datetime
, while the rest is tried to be converted to json if not possible then falling back to using str(x)
if it is json-unconvertable type (like numpy array in my example).您为所需的任何类型提供自定义转换器,如datetime
,而 rest 尝试转换为 json 如果不可能,然后回退到使用str(x)
如果它是 json-unconvertable 类型(如我的示例中的 numpy 数组)。
import json
from datetime import datetime
import numpy as np
obj = {
'time': datetime.now(),
'other': [1,2,3],
'str_conv': np.array([[4,5],[6,7]]),
}
def json_default(x):
if isinstance(x, datetime):
return x.strftime('%H:%M:%S')
else:
try:
json.dumps(x)
return x
except:
return str(x)
print(json.dumps(obj, default = json_default))
output output
{"time": "18:24:57", "other": [1, 2, 3], "str_conv": "[[4 5]\n [6 7]]"}
You can change the output format using strftime().您可以使用 strftime() 更改 output 格式。 It's described here under "Formatting and parsing".它在“格式化和解析”下进行了描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.