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

Python将Excel日期字符串转为可计算数值的问题求助

解决Excel日期字符串转可运算日期的问题

你的问题根源是解析格式字符串和实际日期格式不匹配:你用了%Y-%m-%d(年-月-日),但读取到的日期是Mar 7, 2024这种「英文月份缩写+日+年」的格式,自然解析失败。

正确解析代码

用%b匹配英文月份缩写,%d匹配日期,%Y匹配4位年份,对应格式字符串'%b %d, %Y':

from datetime import datetime

date_str = workbook.active['F12'].value
# 解析为datetime对象
date_fixed = datetime.strptime(date_str, '%b %d, %Y')

额外处理:多语言环境兼容

如果你的运行环境默认不是英文,可能会识别不了英文月份缩写,需要先设置英文locale:

import locale
from datetime import datetime

# 设置英文区域(不同系统写法可能有差异,比如Windows用'en-US')
locale.setlocale(locale.LC_TIME, 'en_US.UTF-8')

date_str = workbook.active['F12'].value
date_fixed = datetime.strptime(date_str, '%b %d, %Y')

导出后确保可运算

解析得到的datetime对象,用openpyxl、pandas等库导出到Excel时,会自动被识别为Excel原生日期格式,此时就能正常执行日期相减等数学运算了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:16:01