【Python】时间戳转日期时间、时间戳转耗时时长

import time


def getTimestamp() -> int:
    '''
    获取当前时间戳,返回13位时间戳(即精确到毫秒)
    :return: eg:1740571096941
    '''
    return int(time.time() * 1000)


def getTime(timestamp: int | None = None) -> str:
    '''
    获取/转换日期时间,返回“年-月-日 时-分-秒.毫秒”
    :param timestamp: 时间戳,若为空则默认为当前时间
    :return: eg:2025-02-26 19:57:05.180
    '''
    if timestamp is None:
        timestamp = getTimestamp()
    return formatTimestamp(timestamp)


def getTimeStr(timestamp: int | None = None) -> str:
    '''
    获取/转换日期时间,返回“【年-月-日 时-分-秒.毫秒】”
    :param timestamp: 时间戳,若为空则默认为当前时间
    :return: eg:【2025-02-26 19:57:05.180】
    '''
    return '【' + getTime(timestamp) + '】'


def formatTimestamp(timestamp: int | None = None) -> str:
    '''
    格式化时间戳
    :param timestamp: 13位时间戳
    :return: eg:2025-02-26 19:57:05.180
    '''
    if timestamp is None:
        timestamp = getTimestamp()
    time_1 = timestamp // 1000
    time_2 = timestamp - time_1 * 1000
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_1)) + "." + str(time_2)


def timestampToTimeConsuming(timestamp: int) -> str:
    '''
    时间戳转为耗时
    :param timestamp: 时间戳
    :return: eg: 1d12h32m45s123ms、1h23m20s、2s
    '''
    if timestamp == 0:
        return '0s'

    result = ''

    oneSecondTimestamp = 1 * 1000
    oneMinuteTimestamp = 60 * oneSecondTimestamp
    oneHourTimestamp = 60 * oneMinuteTimestamp
    oneDayTimestamp = 24 * oneHourTimestamp

    d = 0
    h = 0
    m = 0
    s = 0

    if timestamp >= oneDayTimestamp:
        d = int(timestamp / oneDayTimestamp)
        result += str(d) + 'd'

    timestamp -= d * oneDayTimestamp
    if timestamp >= oneHourTimestamp:
        h = int(timestamp / oneHourTimestamp)
        result += str(h) + 'h'

    timestamp -= h * oneHourTimestamp
    if timestamp >= oneMinuteTimestamp:
        m = int(timestamp / oneMinuteTimestamp)
        result += str(m) + 'm'

    timestamp -= m * oneMinuteTimestamp
    if timestamp >= oneSecondTimestamp:
        s = int(timestamp / oneSecondTimestamp)
        result += str(s) + 's'

    timestamp -= s * oneSecondTimestamp
    if timestamp > 0:
        result += str(timestamp) + 'ms'

    return result

你可能感兴趣的:(Python,python)