You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算当前时间距离上一个整点的已流逝时长

Python计算当前时间与上一个整点时间差的解决方案

直接使用datetime模块处理更简便,也可以适配你现有的time模块写法完成计算,两种方案如下:

方法1:datetime模块实现(更推荐,无需手动处理字符串)

无需先获取整点字符串,直接通过datetime对象的属性替换构造整点时间,相减即可得到时间差:

from datetime import datetime

# 获取当前时间对象
now = datetime.now()
# 构造上一个整点时间(将分、秒、微秒统一置为0)
last_hour = now.replace(minute=0, second=0, microsecond=0)
# 计算时间差
delta = now - last_hour
# 格式化为「00:31」格式的输出
delta_str = f"{delta.seconds//3600:02d}:{(delta.seconds%3600)//60:02d}"
print(delta_str)

方法2:适配你现有time模块的写法

如果你已经通过time.strftime('%H:00:00')拿到了整点字符串,可以将字符串转为时间戳后计算差值:

import time

# 你已经获取到的整点字符串
last_hour_str = time.strftime('%H:00:00')
# 拼接为完整的日期时间字符串,避免跨天计算误差
today_str = time.strftime('%Y-%m-%d')
last_hour_full = f"{today_str} {last_hour_str}"
# 转为时间戳计算差值
last_hour_ts = time.mktime(time.strptime(last_hour_full, '%Y-%m-%d %H:%M:%S'))
now_ts = time.time()
delta_seconds = int(now_ts - last_hour_ts)
# 格式化为目标输出
delta_str = f"{delta_seconds//3600:02d}:{(delta_seconds%3600)//60:02d}"
print(delta_str)

两种方案均符合需求,当前时间为11:31时都会输出00:31

内容的提问来源于stack exchange,提问作者Julian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:39:01