【发布时间】:2022-08-02 21:06:07
【问题描述】:
我有一些代码见 EOM;它绝不是最终的,但它是(到目前为止)我见过/设想的以某种高性能方式验证多种日期格式的最佳方式。
我想知道是否有办法将附加参数传递给这种函数(_normalise_coerce),如果可以在模式中定义日期格式字符串会很好。就像是
{
\"a_date\":{
\"type\": \"datetime\",
\"coerce\": \"to_datetime\",
\"coerce_args\": \"%m/%d/%Y %H:%M\"
}
}
VS 在函数中更改代码以支持额外的日期格式。我浏览了文档,没有发现任何引人注目的东西。相当好的机会,我认为这一切都错了,但认为询问专家是最好的方法。我认为在模式中定义是解决问题的最干净的解决方案,但我对事实、想法和意见全神贯注。
一些上下文:
- 性能至关重要,因为这可能会针对 AWS lambda 中的数百万行运行(而 Cerbie(我对 cerberus 的昵称)并不完全是一只春鸡 :P)。
- 所有模式都不会是原生 python 字典,因为它们都在 JSON/YAML 中定义,因此它们都需要对字符串友好。
- 不使用内置强制,因为无法从字符串中解析 python 类型
- 我不需要 datetime 对象,因此可以使用正则表达式,只是不那么明确且不那么面向未来。
- 如果这一切都错了,我很无能,请温柔(づ。◕‿‿◕。)づ
def _normalize_coerce_to_datetime(self, value: Union(str, datetime, None)) -> Union(datetime, str, None):
\'\'\'
Casts valid datetime strings to the datetime python type.
:param value: (str, datetime, None): python datetime, datetime string
:return: datetime, string, None. python datetime,
invalid datetime string or None if the value is empty or None
\'\'\'
datetime_formats = [\'%m/%d/%Y %H:%M\']
if isinstance(value, datetime):
return value
if value and not value.isspace():
for format in datetime_formats:
try:
return datetime.strptime(value, format)
except ValueError:
date_time = value
return date_time
else:
return None
标签: cerberus