Improvement

If else

def timesince(date):
    now = timezone.now()
    diff = now - date

    if diff.days == 0 and diff.seconds >= 0 and diff.seconds < 60:
        return ' just now'
    if diff.days == 0 and diff.seconds >= 60 and diff.seconds < 3600:
        return str(math.floor(diff.seconds / 60)) + " minutes ago"
    if diff.days == 0 and diff.seconds >= 3600 and diff.seconds < 86400:
        return str(math.floor(diff.seconds / 3600)) + " hours ago"
    if diff.days == 1 and diff.days < 30:
        return str(diff.days) + " day ago"
    if diff.days >= 1 and diff.days < 30:
        return str(diff.days) + " days ago"
    if diff.days >= 30 and diff.days < 365:
        return str(math.floor(diff.days / 30)) + " months ago"
    if diff.days >= 365:
        return str(math.floor(diff.days / 365)) + " years ago"
        
        
        
import bisect

# BREAKPOINTS 必须是已经排好序的,不然无法进行二分查找
BREAKPOINTS = (1, 60, 3600, 3600 * 24)
TMPLS = (
    # unit, template
    (1, "less than 1 second ago"),
    (1, "{units} seconds ago"),
    (60, "{units} minutes ago"),
    (3600, "{units} hours ago"),
    (3600 * 24, "{units} days ago"),
)


def from_now(ts):
    """接收一个过去的时间戳,返回距离当前时间的相对时间文字描述
    """
    seconds_delta = int(time.time() - ts)
    unit, tmpl = TMPLS[bisect.bisect(BREAKPOINTS, seconds_delta)]
    return tmpl.format(units=seconds_delta // unit)
    
    
import time
import datetime
now = time.time()
print(from_now(now))     
print(from_now(now - 24))
print(from_now(now - 600))
print(from_now(now - 7500))
print(from_now(now - 87500))

less than 1 second ago
24 seconds ago
10 minutes ago
2 hours ago
1 days ago

Using Iterable in parameter

def deactivate_users(users: typing.Iterable[str]):
    """批量停用多个用户
    """
    for user in users:
        print(user)
        
        
deactivate_users({1,2,2,3})
deactivate_users(['adf','dfdf'])
# 注:为了加强示例代码的说明性,本文中的部分代码片段使用了Python 3.5
# 版本添加的 Type Hinting 特性

def add_ellipsis(comments: typing.List[str], max_length: int = 12):
    """如果评论列表里的内容超过 max_length,剩下的字符用省略号代替
    """
    index = 0
    for comment in comments:
        comment = comment.strip()
        if len(comment) > max_length:
            comments[index] = comment[:max_length] + '...'
        index += 1
    return comments


comments = [
    "Implementation note",
    "Changed",
    "ABC for generator",
]
print("\n".join(add_ellipsis(comments)))

Implementati...
Changed
ABC for gene...

============================================================

def add_ellipsis_gen(comments: typing.Iterable[str], max_length: int = 12):
    """如果可迭代评论里的内容超过 max_length,剩下的字符用省略号代替
    """
    for comment in comments:
        comment = comment.strip()
        if len(comment) > max_length:
            yield comment[:max_length] + '...'
        else:
            yield comment


print("\n".join(add_ellipsis_gen(comments)))

Implementati...
Changed
ABC for gene...

Last updated