【问题标题】:Naturaltime with minutes, hours, days and weeks自然时间与分钟、小时、天和周
【发布时间】:2016-09-14 12:56:49
【问题描述】:

我在我的 Django 应用程序中使用 naturaltime。

我怎样才能只显示时间,以分钟、小时、天、周为单位?

这是我的代码:

{{ obj.pub_date|naturaltime }}

【问题讨论】:

  • 您忘记添加naturaltime 代码。 ;)
  • 我认为最好使用一些 js 模块,如 momentjs.com,然后你只需在模板中渲染一个日期时间戳,然后让 js 完成剩下的工作。

标签: python django


【解决方案1】:

我使用两个自定义过滤器来解决使用 babel 和 pytz 的非常相似的问题。我写“今天”或“昨天”加上时间。欢迎您以任何您喜欢的方式使用我的代码。

我的模板代码有两种用法,一种用于编写“今天”、“昨天”,或者更早的日期。

{{ scored_document.fields.10.value|format_date_human(locale='en') }}

然后这个标签写的是一天中的实际时间

{{ scored_document.fields.10.value|datetimeformat_list(hour=scored_document.fields.17.value|int ,minute =scored_document.fields.18.value|int, timezoneinfo=timezoneinfo, locale=locale) }}

对应的两个函数是

MONTHS = ('Jan.', 'Feb.', 'Mar.', 'April.', 'May.', 'June.',
          'July.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.')
FORMAT = '%H:%M / %d-%m-%Y'

def format_date_human(to_format, locale='en', timezoneinfo='Asia/Calcutta'):
    tzinfo = timezone(timezoneinfo)
    now = datetime.now()
    #logging.info('delta: %s', str((now - to_format).days))
    #logging.info('delta2: %s', str((datetime.date(now)-datetime.date(to_format)).days))

    if datetime.date(to_format) == datetime.date(now):
        date_str = _('Today')
    elif (now - to_format).days == 1:
        date_str = _('Yesterday')
    else:
        month = MONTHS[to_format.month - 1]
        date_str = '{0} {1}'.format(to_format.day, _(month))
    time_str = format_time(to_format, 'H:mm', tzinfo=tzinfo, locale=locale)
    return "{0}".format(date_str, time_str)



def datetimeformat_list(date, hour, minute, locale='en', timezoneinfo='Asia/Calcutta'):

    import datetime as DT
    import pytz

    utc = pytz.utc
    to_format = DT.datetime(int(date.year), int(date.month), int(date.day), int(hour), int(minute))
    utc_date = utc.localize(to_format)
    tzone = pytz.timezone(timezoneinfo)
    tzone_date = utc_date.astimezone(tzone)
    time_str = format_time(tzone_date, 'H:mm')
    return "{0}".format(time_str)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多