utils/timehelper.py
包含一下功能:

  • 获取最小的 utc 时间,datetime 类型,适用于 mysql 的所有常见,不管是 datime 还是 stamptime
  • 获取当前的 utc 时间,datetime 类型
from datetime import datetime, timedelta, timezone


def get_min_utc_timestamp() -> datetime:
    return (datetime(year=1970, month=1, day=1) + timedelta(seconds=1)).replace(tzinfo=timezone.utc)


def get_utc_now_timestamp() -> datetime:
    """ https://blog.csdn.net/ball4022/article/details/101670024 """
    return datetime.utcnow().replace(tzinfo=timezone.utc)


def timedelta_seconds(start_time: datetime, end_time: datetime = None) -> int:
    """ 返回两个时间相差的秒数 """
    if not end_time:
        end_time = get_utc_now_timestamp()

    return int((end_time - start_time).total_seconds())


def custom_timestamp(base_timestamp: datetime, seconds: int, reduce=False):
    return base_timestamp + timedelta(seconds=seconds) \
        if not reduce \
        else base_timestamp - timedelta(seconds=seconds)


def timestamp_translate_gmt(timestamp: datetime) -> str:
    return timestamp.strftime('%a, %d %b %Y %H:%M:%S GMT')


def timestamp_translate_iso_8601(timestamp: datetime, include_millisecond: bool = False, include_timezone: bool = False) -> str:
    if include_timezone:
        if not timestamp.tzinfo:
            raise ValueError(
                'The timestamp parameter does not contain time zone information')
        return timestamp.strftime("%Y-%m-%d %H:%M:%S.%f%z")

    if include_millisecond:
        return timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')

    return timestamp.strftime('%Y-%m-%d %H:%M:%S')


universe_king
3.4k 声望680 粉丝