anb*_*ian 3 python datetime date strftime pandas
我的日期格式11122020
在 pandas 列中采用格式(ddmmyyyy)。
我用
datapdf["wholetime"]=pd.to_datetime(datapdf["wholetime"],format='%d%m%Y)
Run Code Online (Sandbox Code Playgroud)
转换为时间并按时间进行处理。
最近我的代码在日期 3122020 上失败了
ValueError: day is out of range for month
Run Code Online (Sandbox Code Playgroud)
python 解释为 31 2 2020 而不是 3 12 2020 导致错误。有人对此有解决方案吗?
一种方法是使用str.zfill
以确保日期为 8 位数字:
s = pd.Series(["11122020", "3122020"])
pd.to_datetime(s.str.zfill(8), format="%d%m%Y")
Run Code Online (Sandbox Code Playgroud)
输出:
0 2020-12-11
1 2020-12-03
dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
请注意,此答案仅涉及当天缺少 0。它将无法解析更模糊的项目,例如332020
,其中月份部分也需要标题 0。