time.py 1.75 KB
# coding=utf-8
from __future__ import absolute_import

import time
import datetime
import random


def get_timestamp_or_none(the_time):
    return get_timestamp(the_time) if the_time is not None else None


def get_timestamp(the_time):
    if the_time is None:
        return None
    return get_timestamp_epoch(the_time) + 8 * 3600


def get_timestamp_epoch(the_time):
    if the_time is None:
        return None

    if isinstance(the_time, datetime.datetime):
        pass
    elif isinstance(the_time, datetime.date):
        # TODO: 是这样算的么?
        the_time = datetime.datetime(
            the_time.year, the_time.month, the_time.day)
    else:
        raise TypeError(
            "datetime.datetime or datetime.date expected. [%s]" % type(the_time))
    return int((the_time - datetime.datetime.fromtimestamp(0)).total_seconds())


def get_humanize_datetime(d):
    now = datetime.datetime.now()

    dtime = int((now - d).total_seconds())
    if dtime < 60:
        return u'刚刚'

    elif 60 <= dtime < 60 * 60:
        return u'{}分钟前'.format(int(dtime / 60))

    elif 60 * 60 <= dtime < 60 * 60 * 24:
        return u'{}小时前'.format(int(dtime / (60 * 60)))

    elif 60 * 60 * 24 <= dtime < 60 * 60 * 24 * 30:
        return u'{}天前'.format(int(dtime / (60 * 60 * 24)))

    else:
        return u'{}个月前'.format(int(dtime / (60 * 60 * 24 * 30)))


def get_daytime_countdown(start, end):
    # 只返回未来日子8点到23点之间的countdown
    countdown = random.randint(start, end)
    now = time.time()
    hour = datetime.datetime.fromtimestamp(now + countdown).hour
    while not (8 <= hour <= 23):
        countdown = random.randint(start, end)
        hour = datetime.datetime.fromtimestamp(now + countdown).hour
    return countdown