当前位置:天才代写 > tutorial > Python教程 > python 友好日期展示函数-python手艺人

python 友好日期展示函数-python手艺人

2021-02-22 10:17 星期一 所属: Python教程 浏览:736

情况

blog中发布的文章内容日期怎样才能更强的表明给客户?实际上甚少或微信朋友圈中经常会应用的日期表明文件格式如:刚、五分钟内、1小时前等,今日就来给大伙儿共享一个友善展现日期的python函数

构思

依据日期主要参数与获取当前时间做比照,随后回到特殊文件格式的字符串数组就可以

完成

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(int(second_diff / 60))   " minutes ago"
        if second_diff < 7200:
            return "an hour ago"
        if second_diff < 86400:
            return str(int(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(int(day_diff / 7))   " weeks ago"
    if day_diff < 365:
        return str(int(day_diff / 30))   " months ago"
    return str(int(day_diff / 365))   " years ago"
 

    关键字:

天才代写-代写联系方式