如何在Python中将特定格式的时间字符串转换为epoch时间?
将特定格式的时间字符串转换为Epoch时间(Python实现)
你的时间字符串格式为"2023-01-1T17:35:19.818",可以通过以下两种Python方法转换为Epoch时间(即从1970-01-01 00:00:00 UTC到指定时间的秒数,带小数表示毫秒):
方法一:使用标准库datetime
无需额外安装依赖,通过指定格式字符串解析时间后转换:
from datetime import datetime date_time = "2023-01-1T17:35:19.818" # 按对应格式解析时间字符串 dt_object = datetime.strptime(date_time, "%Y-%m-%dT%H:%M:%S.%f") # 转换为Epoch时间 epoch_time = dt_object.timestamp() print(epoch_time) # 输出示例:1672601719.818
- 格式字符串说明:
%Y(4位年份)、%m(2位月份)、%d(日,支持1位或2位数字)、%H:%M:%S(时分秒)、%f(微秒,输入的3位毫秒会自动补零到6位) - 如果需要整数秒的Epoch时间,可使用
int(epoch_time)
方法二:使用python-dateutil自动解析
如果不想手动编写格式字符串,可借助python-dateutil库自动识别格式:
- 先安装依赖:
pip install python-dateutil
- 编写代码:
from dateutil import parser date_time = "2023-01-1T17:35:19.818" dt_object = parser.parse(date_time) epoch_time = dt_object.timestamp() print(epoch_time)
注意事项
如果你的时间字符串默认是UTC时间而非本地时间,需要手动指定时区以避免转换误差:
from datetime import datetime, timezone # 方法一指定UTC时区 dt_object = datetime.strptime(date_time, "%Y-%m-%dT%H:%M:%S.%f").replace(tzinfo=timezone.utc) epoch_time = dt_object.timestamp()
内容的提问来源于stack exchange,提问作者user18148705
相关产品推荐
相关产品推荐

