使用pd.to_datetime转换numpy字符串数组为datetime格式时格式匹配报错
解决numpy字符串数组转datetime格式匹配报错问题
排查数据中的异常格式条目
报错未必是指定格式错误,可能数组里混有不符合格式的字符串。用以下代码定位问题内容:import datetime import numpy as np for s in temp_time: try: datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f") except ValueError: print(f"格式不匹配的内容:{s}")清理字符串隐藏空格
数组中的字符串可能带有首尾隐藏空格,导致格式匹配失败。先去除空格再转换:temp_time_clean = np.char.strip(temp_time) temp_datetime = pd.to_datetime(temp_time_clean, format="%Y-%m-%d %H:%M:%S.%f")让pandas自动推断格式
确认所有数据格式统一的话,可以不指定format参数,让pandas自动识别格式,规避手动写格式的误差:temp_datetime = pd.to_datetime(temp_time)
内容的提问来源于stack exchange,提问作者willard
相关产品推荐
相关产品推荐

