如何针对epoch时间戳实现多单位人类可读时间差计算(优先Bash/Golang/Python)
多粒度组合时间差实现方案
核心计算规则
为匹配报表场景的展示要求,所有计算严格遵循以下规则:
- 单位层级从高到低为:年、月、周、天、小时,所有层级只输出整数结果,不保留小数
- 年、月的计算基于实际日历长度累加,而非固定用365天/年、30天/月做硬换算,从根源避免「1.06个月前」这类非预期结果
- 最小统计粒度为小时,秒、分钟级的差值直接截断为整数小时,不纳入输出
- 0值的层级直接过滤,不强制输出,比如差1年3周,不额外拼接0个月、0天、0小时的内容
- 最终输出格式匹配示例要求:
上次运行:X年、Y个月、Z周、A天、B小时前
适配方案(按优先顺序排列)
Python 实现(无额外依赖,适配性最高)
使用Python标准库实现,无需安装第三方包,原生处理闰年、大小月的日期溢出问题,可直接嵌入报表脚本使用。
from datetime import datetime, timedelta def calc_diff(target_time_str, fmt="%Y-%m-%dT%H:%M:%S"): target_t = datetime.strptime(target_time_str, fmt) now_t = datetime.now() diff_parts = [] # 逐次累加计算年偏移 years = 0 temp_t = target_t while True: try: next_t = temp_t.replace(year=temp_t.year + 1) except ValueError: # 处理闰年2月29日的特殊场景 next_t = temp_t.replace(year=temp_t.year + 1, day=28) if next_t <= now_t: years +=1 temp_t = next_t else: break if years >0: diff_parts.append(f"{years}年") # 逐次累加计算月偏移 months =0 while True: next_year = temp_t.year + (temp_t.month +1 -1)//12 next_month = (temp_t.month +1 -1) %12 +1 try: next_t = temp_t.replace(year=next_year, month=next_month) except ValueError: # 处理大小月日期溢出(如1月31日顺延到2月) next_t = temp_t.replace(year=next_year, month=next_month, day=28) if next_t <= now_t: months +=1 temp_t = next_t else: break if months>0: diff_parts.append(f"{months}个月") # 拆分周、天的差值 total_days = (now_t - temp_t).days weeks = total_days //7 remain_days = total_days %7 if weeks>0: diff_parts.append(f"{weeks}周") if remain_days>0: diff_parts.append(f"{remain_days}天") # 计算剩余小时差值 remain_seconds = (now_t - temp_t - timedelta(days=total_days)).total_seconds() hours = int(remain_seconds // 3600) if hours>0: diff_parts.append(f"{hours}小时") if not diff_parts: return "上次运行:刚刚" return f"上次运行:{'、'.join(diff_parts)}前" # 测试逻辑 if __name__ == "__main__": test_times = ["2020-03-19T05:12:14", "2019-08-27T08:47:27", "2020-05-12T11:10:18", "2020-02-01T07:40:01"] for t in test_times: print(f"输入时间:{t} → 输出:{calc_diff(t)}")
Bash 实现(纯系统命令,适配无Python环境的服务器)
基于GNU原生date工具实现,无需安装额外软件包,支持直接在Shell脚本中调用处理ISO格式时间戳。
#!/bin/bash # 入参为ISO格式时间字符串,例如 "2020-03-19T05:12:14" get_diff_str() { local input_t="$1" local now_ts=$(date +%s) local temp_ts=$(date -d "$input_t" +%s) local parts=() # 计算年偏移 local years=0 while true; do local next_ts=$(date -d "@$temp_ts +1 year" +%s) if [ "$next_ts" -le "$now_ts" ]; then ((years++)) temp_ts=$next_ts else break fi done [ "$years" -gt 0 ] && parts+=("${years}年") # 计算月偏移 local months=0 while true; do local next_ts=$(date -d "@$temp_ts +1 month" +%s) if [ "$next_ts" -le "$now_ts" ]; then ((months++)) temp_ts=$next_ts else break fi done [ "$months" -gt 0 ] && parts+=("${months}个月") # 拆分周、天差值 local remain_sec=$((now_ts - temp_ts)) local total_days=$((remain_sec / 86400)) local weeks=$((total_days /7)) local remain_days=$((total_days %7)) [ "$weeks" -gt 0 ] && parts+=("${weeks}周") [ "$remain_days" -gt 0 ] && parts+=("${remain_days}天") # 计算剩余小时 local remain_hour=$(( (remain_sec - total_days*86400) / 3600 )) [ "$remain_hour" -gt 0 ] && parts+=("${remain_hour}小时") # 拼接最终输出 if [ ${#parts[@]} -eq 0 ]; then echo "上次运行:刚刚" else local joined=$(IFS="、"; echo "${parts[*]}") echo "上次运行:${joined}前" fi } # 测试调用示例 # get_diff_str "2020-03-19T05:12:14"
Golang 实现(适合嵌入服务端报表场景)
基于Go标准库实现,无外部依赖,可直接打包为独立可执行文件接入现有报表系统。
package main import ( "fmt" "time" ) func calcDiff(inputT string) string { targetT, _ := time.Parse("2006-01-02T15:04:05", inputT) nowT := time.Now() var parts []string // 计算年偏移 years := 0 tempT := targetT for { nextT := tempT.AddDate(1, 0, 0) if nextT.Before(nowT) || nextT.Equal(nowT) { years++ tempT = nextT } else { break } } if years > 0 { parts = append(parts, fmt.Sprintf("%d年", years)) } // 计算月偏移 months := 0 for { nextT := tempT.AddDate(0, 1, 0) if nextT.Before(nowT) || nextT.Equal(nowT) { months++ tempT = nextT } else { break } } if months > 0 { parts = append(parts, fmt.Sprintf("%d个月", months)) } // 拆分周、天差值 duration := nowT.Sub(tempT) totalDays := int(duration.Hours() / 24) weeks := totalDays / 7 remainDays := totalDays %7 if weeks >0 { parts = append(parts, fmt.Sprintf("%d周", weeks)) } if remainDays >0 { parts = append(parts, fmt.Sprintf("%d天", remainDays)) } // 计算剩余小时 remainHours := int((duration - time.Duration(totalDays)*24*time.Hour).Hours()) if remainHours >0 { parts = append(parts, fmt.Sprintf("%d小时", remainHours)) } if len(parts) ==0 { return "上次运行:刚刚" } res := "上次运行:" for i, s := range parts { if i>0 { res += "、" } res += s } return res + "前" } func main() { testTimes := []string{"2020-03-19T05:12:14", "2019-08-27T08:47:27", "2020-05-12T11:10:18", "2020-02-01T07:40:01"} for _, t := range testTimes { fmt.Printf("输入时间:%s → 输出:%s\n", t, calcDiff(t)) } }
注意事项
- 所有实现默认使用服务器本地时区,如果需要统一展示UTC时间,仅需将代码中的时间获取逻辑替换为对应时区的时间即可,核心计算逻辑无需调整
- 对比传统硬算秒差的方式,上述实现会自动识别实际日历的月长差异,比如从1月15日到2月14日算1个月,不会因为2月只有28/29天就出现折算的小数月长
- 针对用户提到的16天差的场景,逻辑会自动拆分为2周2天,不会输出单单位的16天结果
内容的提问来源于stack exchange,提问作者Byron Mansfield
相关产品推荐
相关产品推荐

