2016-09-14 153 views
0

我在我的Django應用程序中使用自然時間。自然時間與分鐘,小時,天和星期

我怎樣才能以分鐘顯示時間,然後是幾小時,幾天,幾周?

這裏是我的代碼:

{{ obj.pub_date|naturaltime }} 
+0

你忘了加上'naturaltime'代碼。 ;) – allcaps

+0

我相信這是最好的使用像http://momentjs.com/一些js模塊,然後你只是在你的模板中呈現日期時間戳,讓js完成剩下的工作。 – allcaps

回答

0

我用兩個自定義過濾器使用巴貝爾和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) 
相關問題