项目中关于时区的一点点tips

import pytz
WORK_TIMEZONE = pytz.timezone('Asia/Shanghai')

class DateTimeTool(object):

    @staticmethod
    def timestamp():
        now_dt = datetime.utcnow()
        ts = (now_dt - datetime(1970, 1, 1)).total_seconds()
        return ts

    @staticmethod
    def format_date(ts, fmt='%Y-%m-%d'):
        date = datetime.utcfromtimestamp(ts + tzoffset)
        return date.strftime(fmt)

    @staticmethod
    def expire_days(now, expire):
        if now - expire < 0:
            return 0
        if now - expire < 86400:
            return 1
        else:
            return timedelta(seconds=(now-expire)).days

    @staticmethod
    def expire_seconds(ts):
        sec = ts % 86400 /3600
        #0:00~8:00 to 9:00
        if sec>=16:
            return int(ts/86400 + 1)*86400 + 3600
        return ts

    @staticmethod
    def date(tz=WORK_TIMEZONE):
        return datetime.fromtimestamp(time.time(), tz=tz)

    @staticmethod
    def beijing_date():
        ts = int(time.time())
        dt = DateTimeTool.format_date(ts, fmt='%Y年%m月%d日')
        return dt

    @staticmethod
    def parse_beijing_date(date_str, fmt='%Y年%m月%d日'):
        """
        weekday = DateTimeTool.parse_beijing_date(start_date).weekday()
        weekday_chinese = {
            0: u'一', 1: u'二', 2: u'三', 3: u'四', 4: u'五', 5: u'六', 6: u'日'
        }[weekday]
        :param date_str:
        :param fmt:
        :return:
        """
        date_str = to_str(date_str)
        try:
            result = datetime.strptime(date_str, fmt)
        except Exception as e:
            logger.exception(e)
            result = dateparser.parse(date_str)
        return result

你可能感兴趣的:(项目中关于时区的一点点tips)