【问题标题】:How to format dates in colander validator?如何在滤锅验证器中格式化日期?
【发布时间】:2019-03-01 04:23:49
【问题描述】:

用户 Pyramid、Colander 和 Deform,我有一个日期时间小部件。

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 必须在 2018 年 1 月 1 日凌晨 12:00 之后

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

【问题讨论】:

  • -07:53 作为时区看起来根本不正确
  • 该区域表明您正在使用 pytz 没有经过适当的规范化
  • 确实如此。在提出这个问题之后,我了解到 pytz 在_tzinfos 中有一个时区列表,其中包括一个过时的本地平均时间 (LMT),它成为默认值,因为它在列表中是第一个。我最终解决了所有问题,如下面的回答所示。

标签: pyramid deform colander


【解决方案1】:

这是我最终使用的。关键是不要使用默认变量 ${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 中的最小和最大日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2021-05-29
    • 2016-05-11
    • 1970-01-01
    相关资源
    最近更新 更多