将时间戳转换成天时分秒格式

def timestamp_difference_to_dhms(timestamp1, timestamp2):
    # 将时间戳转换为 datetime 对象
    # # 13位时间戳会报错
    if len(str(timestamp1)) == 13:
        timestamp1 = timestamp1 / 1000
    if len(str(timestamp2)) == 13:
        timestamp2 = timestamp2 / 1000

    dt1 = datetime.fromtimestamp(timestamp1)
    dt2 = datetime.fromtimestamp(timestamp2)

    # 计算时间差
    delta = dt2 - dt1

    # 提取天数、秒数和微秒数
    days = delta.days
    seconds = delta.seconds
    microseconds = delta.microseconds

    # 计算小时、分钟和秒数
    hours, remainder = divmod(seconds, 3600)
    minutes, seconds = divmod(remainder, 60)

    return f"{days}天{hours}小时{minutes}分钟{seconds}秒"

 

posted @ 2024-03-22 14:14  你说夕阳很美  阅读(115)  评论(0)    收藏  举报