SORU
11 EKİM 2009, Pazar


Python ile kullanıcı dostu bir saat biçimi?

Python: dosya değişiklik zamanları göstermeliyim "1 gün önce", "iki saat önce" biçim.

Bir şey yapmak için hazır var mı? İngilizce olmalı

CEVAP
11 EKİM 2009, Pazar


Yes, there is. Ya da, kendi yazmak ve ihtiyaçlarınıza göre uyarlamak.


Nov 30 DÜZENLEYİN:Bağlı işlev blog yazarı silinmiş olarak post taşındı.

def pretty_date(time=False):
    """
    Get a datetime object or a int() Epoch timestamp and return a
    pretty string like 'an hour ago', 'Yesterday', '3 months ago',
    'just now', etc
    """
    from datetime import datetime
    now = datetime.now()
    if type(time) is int:
        diff = now - datetime.fromtimestamp(time)
    elif isinstance(time,datetime):
        diff = now - time
    elif not time:
        diff = now - now
    second_diff = diff.seconds
    day_diff = diff.days

    if day_diff < 0:
        return ''

    if day_diff == 0:
        if second_diff < 10:
            return "just now"
        if second_diff < 60:
            return str(second_diff)   " seconds ago"
        if second_diff < 120:
            return "a minute ago"
        if second_diff < 3600:
            return str(second_diff / 60)   " minutes ago"
        if second_diff < 7200:
            return "an hour ago"
        if second_diff < 86400:
            return str(second_diff / 3600)   " hours ago"
    if day_diff == 1:
        return "Yesterday"
    if day_diff < 7:
        return str(day_diff)   " days ago"
    if day_diff < 31:
        return str(day_diff / 7)   " weeks ago"
    if day_diff < 365:
        return str(day_diff / 30)   " months ago"
    return str(day_diff / 365)   " years ago"

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • metallmanutza13

    metallmanutz

    13 NİSAN 2007
  • oHeymarvin

    oHeymarvin

    11 Temmuz 2013
  • xXGAMERrs_Xx

    xXGAMERrs_Xx

    31 Temmuz 2014