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

Python中使用纪元秒数计算纪元天数、年数及时分秒的小时计算问题求助

Python中使用纪元秒数计算纪元天数、年数及时分秒的小时计算问题求助

嘿,我仔细看了你的代码和遇到的问题,咱们来一步步拆解下为什么小时部分的结果不符合你的预期~

首先先把你的代码贴出来方便分析:

import time

#Program is supposed to use epoch time to accurately display to
#user the amount of days since epoch, years since epoch and 
#display the time hours, minutes and seconds.

epoch = time.time()#get amount fo seconds that passed since epoch
hour_seconds     = 3600
day_in_seconds   = hour_seconds * 24
days_since_epoch = int(epoch//day_in_seconds)
print(days_since_epoch,"days")
years_since_epoch = int(epoch//(day_in_seconds * 365))
print(years_since_epoch,"years")
remainder = int(epoch % day_in_seconds)
print(remainder)
hours = remainder // hour_seconds
print(hours)
new_remainder = remainder % hour_seconds
minutes =     new_remainder // 60
print(minutes)
seconds = new_remainder % 60
print(seconds)

先理清楚核心问题:你说分钟和秒的计算是对的,但小时显示有问题,结合你给出的期望输出,我觉得可能有两个原因,咱们一个个说:

原因1:输出格式不符合预期,而非计算错误

看你的期望输出是22 , hours,但你的代码里只是直接print(hours),输出的只有数字22,没有后面的格式内容。如果你是因为这个觉得“程序不工作”,那只需要修改小时的输出语句,调整成你想要的格式就行:

print(f"{hours} , hours")

原因2:时区偏差导致计算出的小时是UTC时间,而非你期望的本地时间

time.time()返回的是**UTC(协调世界时)**的纪元秒数,如果你期望的是本地时间的小时,那直接用这个值计算出来的小时就会和你本地时间有偏差(比如你在东八区的话,UTC时间比本地晚8小时,计算出的小时就会比本地时间少8)。

这种情况的话,有两种解决办法:

办法一:用time.localtime()直接获取本地时间的时分秒

Python的time.localtime()可以直接把纪元秒数转换成本地时间的结构化信息,用这个方法能省掉手动计算的麻烦,还能自动处理时区和夏令时:

# 替换你代码中从remainder开始的部分
local_time_struct = time.localtime(epoch)
hours = local_time_struct.tm_hour
minutes = local_time_struct.tm_min
seconds = local_time_struct.tm_sec

# 按照你的期望格式输出
print(f"{remainder} time of day in seconds")
print(f"{hours} , hours")
print(f"{minutes} minutes.")
print(f"{seconds} seconds")

办法二:手动调整时区偏移

如果你还是想自己手动计算,可以把本地时区和UTC的偏移秒数加进去,修正当天的剩余秒数:

# 获取本地时区与UTC的偏移秒数(自动适配夏令时)
# time.altzone是UTC减去本地时间的秒数,所以本地时间 = UTC时间 + 偏移值
timezone_offset = -time.altzone

# 修正后的当天剩余秒数(本地时间)
remainder = int((epoch + timezone_offset) % day_in_seconds)

# 后面的计算和你原来的逻辑一样
hours = remainder // hour_seconds
new_remainder = remainder % hour_seconds
minutes = new_remainder // 60
seconds = new_remainder % 60

# 格式化输出
print(f"{remainder} time of day in seconds")
print(f"{hours} , hours")
print(f"{minutes} minutes.")
print(f"{seconds} seconds")

另外提个小细节:你用epoch//(day_in_seconds * 365)计算年数的方式会忽略闰年,实际每年的平均天数是365.2425天,所以长期来看这个数值会有误差,但如果只是近似计算的话,这个方法也够用~

备注:内容来源于stack exchange,提问作者Andre Cepin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:02:58