如何在漏勺验证器中格式化日期?

时间:2018-09-25 13:55:29

标签: pyramid deform colander

用户金字塔,漏勺和变形,我有一个日期时间小部件。

datetime_event = colander.SchemaNode(
    colander.DateTime(),
    validator=colander.Range(
        min=datetime(
            2018, 1, 1, 0, 0,
            tzinfo=timezone.utc),
        min_err=(
            '${val} must be after ${min}'),
        max=datetime.now(timezone.utc),
        max_err=(
            '${val} is in the future, and must be less than ${max}')
    ),
)

我收到此用户敌对的验证错误消息。

  

2017-08-21 05:00:00-07:53必须在2018-01-01 00:00:00 + 00:00之后

我想格式化不带时区内容的日期:

  

2017-08-21 05:00:00必须在2018-01-01 00:00:00之后

或更妙的是:

  

2017年8月21日5:00 AM必须在2018年1月1日12:00 AM之后

如果可能的话,我该如何格式化min_errmax_err中的日期时间对象?

1 个答案:

答案 0 :(得分:0)

这就是我最终使用的。关键是不要使用默认变量${val}并使用普通的旧Python f字符串。

tz = self.tz
days_before = 28
dtmin = local_days_before(tz, days_before)  # localized min date
dtmax = datetime.now(utc).astimezone(tz)
datetime_event = colander.SchemaNode(
    colander.DateTime(default_tzinfo=dtmax.tzinfo),
    widget=deform.widget.DateTimeInputWidget(
        date_options={'min': -days_before,
                      'max': True,
                      'format': 'yyyy-mm-dd'},
        time_options={'format': 'HH:i',
                      'formatLabel': 'HH:i'},
    ),
    validator=colander.Range(
        min=dtmin,
        min_err=(f"Datetime must be after "
                 f"{dtmin:%B %d, %Y, %-I:%M %p} "),
        max=dtmax,
        max_err=(f"Datetime must be before "
                 f"{dtmax: %B %d, %Y, %-I:%M %p}")
    ),
    title='Date and Time',
    description='Date and time when the event occurred'
)

此解决方案还实现了Pickadate UI中日期和时间以及最小和最大日期的格式。