【问题标题】:Django: DurationField with resolution in microsecondsDjango:分辨率为微秒的 DurationField
【发布时间】:2018-04-12 09:14:32
【问题描述】:

django DurationField 在 django 管理界面中仅显示 HH:MM:SS。

不幸的是,在我目前的情况下,这还不够。

我需要能够在管理界面中显示/编辑微秒。

这是怎么做到的?

更新

这是一个错误。我在数据库中的数据是错误的。在数据进入数据库之前在进程中删除的微秒数。

如果有的话,Django 会显示微秒。您无需执行任何操作即可显示它们。

【问题讨论】:

    标签: django datetime django-admin


    【解决方案1】:

    查看来源:

    https://docs.djangoproject.com/en/2.0/_modules/django/db/models/fields/#DurationField

    我认为方法是覆盖forms.DurationField (https://docs.djangoproject.com/en/2.0/_modules/django/forms/fields/#DurationField) 并准确地说是这些方法:

    from django.utils.duration import duration_string

    def duration_string(duration):
        """Version of str(timedelta) which is not English specific."""
        days, hours, minutes, seconds, microseconds = _get_duration_components(duration)
    
        string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
        if days:
            string = '{} '.format(days) + string
        if microseconds:
            string += '.{:06d}'.format(microseconds)
    
        return string
    

    请注意,可能也需要覆盖这些 django.utils.dateparse.parse_duration

    def parse_duration(value):
        """Parse a duration string and return a datetime.timedelta.
    
        The preferred format for durations in Django is '%d %H:%M:%S.%f'.
    
        Also supports ISO 8601 representation and PostgreSQL's day-time interval
        format.
        """
        match = standard_duration_re.match(value)
        if not match:
            match = iso8601_duration_re.match(value) or postgres_interval_re.match(value)
        if match:
            kw = match.groupdict()
            days = datetime.timedelta(float(kw.pop('days', 0) or 0))
            sign = -1 if kw.pop('sign', '+') == '-' else 1
            if kw.get('microseconds'):
                kw['microseconds'] = kw['microseconds'].ljust(6, '0')
            if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):
                kw['microseconds'] = '-' + kw['microseconds']
            kw = {k: float(v) for k, v in kw.items() if v is not None}
            return days + sign * datetime.timedelta(**kw)
    

    【讨论】:

      猜你喜欢
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 2011-01-25
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多