User-friendly time format in Python?

后端 未结 14 1524
[愿得一人]
[愿得一人] 2020-12-12 10:06

Python: I need to show file modification times in the \"1 day ago\", \"two hours ago\", format.

Is there something ready to do that? It should be in English.

14条回答
  •  情书的邮戳
    2020-12-12 11:02

    In looking for the same thing with the additional requirement that it handle future dates, I found this: http://pypi.python.org/pypi/py-pretty/1

    Example code (from site):

    from datetime import datetime, timedelta
    now = datetime.now()
    hrago = now - timedelta(hours=1)
    yesterday = now - timedelta(days=1)
    tomorrow = now + timedelta(days=1)
    dayafter = now + timedelta(days=2)
    
    import pretty
    print pretty.date(now)                      # 'now'
    print pretty.date(hrago)                    # 'an hour ago'
    print pretty.date(hrago, short=True)        # '1h ago'
    print pretty.date(hrago, asdays=True)       # 'today'
    print pretty.date(yesterday, short=True)    # 'yest'
    print pretty.date(tomorrow)                 # 'tomorrow'
    

提交回复
热议问题