来源:
'https://yuanbao.tencent.com/bot/app/share/chat/1d7lG7AmkkSD','https://yuanbao.tencent.com/bot/app/share/chat/ANFM2jdRrRIv',
'https://yuanbao.tencent.com/bot/app/share/chat/TcAcJYPxeESS','https://yuanbao.tencent.com/bot/app/share/chat/CLskLhLOfUuo',
'https://yuanbao.tencent.com/bot/app/share/chat/1QQHShMDKyYk','https://yuanbao.tencent.com/bot/app/share/chat/M7nVKaeJtZmT',
from datetime import datetime, timedelta
# 创建两个datetime对象
start_time = datetime(2023, 5, 10, 9, 30, 0)
end_time = datetime(2023, 5, 12, 15, 45, 30)
# 计算时间差
time_difference = end_time - start_time
print(f"时间差: {time_difference}")
print(f"天数: {time_difference.days}")
print(f"秒数: {time_difference.seconds}")
print(f"总秒数: {time_difference.total_seconds():.2f}")
输出结果:
时间差: 2 days, 6:15:30
天数: 2
秒数: 22530 (6小时15分30秒)
总秒数: 192930.00
timedelta对象有三个主要属性:
days
- 天数 (可为负数)seconds
- 秒数 (0-86399)microseconds
- 微秒数 (0-999999)使用total_seconds()
方法获取总秒数(包含天数转换的秒数)
import time
from datetime import datetime
start = datetime.now()
# 模拟耗时操作
time.sleep(2.5) # 休眠2.5秒
end = datetime.now()
elapsed = end - start
print(f"程序执行时间: {elapsed.total_seconds():.3f}秒")
now = datetime.now()
# 计算10天后的日期
future_date = now + timedelta(days=10)
print(f"10天后: {future_date.strftime('%Y-%m-%d')}")
# 计算3周前的日期
past_date = now - timedelta(weeks=3)
print(f"3周前: {past_date.strftime('%Y-%m-%d')}")
# 计算精确时间偏移
future_time = now + timedelta(days=2, hours=5, minutes=30)
print(f"2天5小时30分钟后: {future_time.strftime('%Y-%m-%d %H:%M:%S')}")
def format_timedelta(delta):
total_seconds = int(delta.total_seconds())
days, remainder = divmod(total_seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
parts = []
if days: parts.append(f"{days}天")
if hours: parts.append(f"{hours}小时")
if minutes: parts.append(f"{minutes}分")
if seconds or not parts: parts.append(f"{seconds}秒")
return "".join(parts)
# 测试函数
delta1 = timedelta(days=1, hours=5, minutes=42, seconds=15)
delta2 = timedelta(minutes=45, seconds=30)
print(format_timedelta(delta1)) # 输出: 1天5小时42分15秒
print(format_timedelta(delta2)) # 输出: 45分30秒
使用时间戳(自1970年1月1日UTC以来的秒数)计算时间差:
import time
# 获取当前时间戳
start_timestamp = time.time()
# 执行操作
time.sleep(1.5) # 休眠1.5秒
# 获取结束时间戳
end_timestamp = time.time()
# 计算时间差(秒)
time_diff = end_timestamp - start_timestamp
print(f"操作耗时: {time_diff:.3f}秒")
print(f"等价于 {time_diff * 1000:.2f} 毫秒")
pytz
库或Python 3.9+的zoneinfo
模块total_seconds()
获取精确的时间差(包含天数)time.monotonic()
避免系统时间调整的影响strftime
方法原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。