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

如何在Python中将S3获取的datetime转换为Unix epoch时间戳

Python将S3返回的时间转换为Unix时间戳方案

报错原因

你使用的strtotime是PHP的时间解析方法,Python标准库datetime模块未提供该接口,因此会抛出"type object 'datetime.datetime' has no attribute 'strtotime'"错误。

最优实现方案(无需转字符串)

S3返回的s3_object.last_modified本身就是带UTC时区的datetime对象,无需转字符串再解析,直接调用timestamp()方法即可得到Unix时间戳:

s3_object = s3_resource.Object("testunzipping", "DataPump_10000838.zip")
last_modified = s3_object.last_modified
# 直接获取Unix时间戳(浮点数,精确到微秒)
unix_timestamp = last_modified.timestamp()
# 如需整数秒级时间戳,做类型转换即可
unix_timestamp_int = int(unix_timestamp)

注意:S3返回的last_modified默认是UTC时区的感知型(aware)datetime对象,调用timestamp()时会自动计算正确的时间偏移,无需手动处理时区。

字符串转时间戳方案

如果你已经将datetime对象转为了2021-10-20 15:42:40+00:00格式的字符串,可以按如下方式解析转换:

Python 3.7及以上版本

直接使用fromisoformat解析标准ISO格式时间字符串:

import datetime

last_modified_str = "2021-10-20 15:42:40+00:00"
dt_obj = datetime.datetime.fromisoformat(last_modified_str)
unix_timestamp = dt_obj.timestamp()

Python 3.6及以下版本

使用strptime指定格式解析:

import datetime

last_modified_str = "2021-10-20 15:42:40+00:00"
dt_obj = datetime.datetime.strptime(last_modified_str, "%Y-%m-%d %H:%M:%S%z")
unix_timestamp = dt_obj.timestamp()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:09:04