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

如何获取当前日期时间的Epoch时间及30天前的Epoch时间?

获取当前及30天前后的Epoch时间

问题说明

你需要实现两个需求:

  • 获取当前日期时间对应的Epoch时间(变量x)
  • 计算当前Epoch时间与30天前Epoch时间的差值(变量y)

原代码问题修正

你提供的代码存在两处错误:

  • 未导入datetime模块却调用了datetime.now()
  • 试图将datetime对象传入time.strptime(),但该函数仅接受字符串类型的时间格式

以下是修正并优化后的代码:

import time
from datetime import datetime, timedelta

# 获取当前Epoch时间(x)
current_epoch = int(time.time())
print(f"当前Epoch时间: {current_epoch}")

# 计算30天前的datetime对象
thirty_days_ago = datetime.now() - timedelta(days=30)
# 转换为Epoch时间
thirty_days_ago_epoch = int(time.mktime(thirty_days_ago.timetuple()))

# 计算时间差(y)
time_difference = current_epoch - thirty_days_ago_epoch
print(f"当前与30天前的Epoch时间差: {time_difference} 秒")

代码解释

  • time.time():直接返回当前时间的Epoch时间戳(浮点数),转换为整数得到精确到秒的结果
  • timedelta(days=30):便捷计算指定天数前的datetime对象,无需手动计算日期
  • time.mktime():将datetime对象转换为对应的Epoch时间戳

简化实现(仅用datetime模块)

如果你不想导入time模块,可以直接使用datetime的timestamp()方法:

from datetime import datetime, timedelta

current_epoch = int(datetime.now().timestamp())
thirty_days_ago_epoch = int((datetime.now() - timedelta(days=30)).timestamp())
time_difference = current_epoch - thirty_days_ago_epoch

print(f"当前Epoch时间: {current_epoch}")
print(f"时间差: {time_difference} 秒")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:35:29