使用pd.to_datetime转换时间戳报错:time data ' '不匹配格式%Y%m%d:%H%M
解决方法
错误提示time data '\r' does not match format说明你的time列中存在仅含回车符\r的行,大概率是CSV数据里的空行或者换行符处理不当导致的。可以按以下步骤修复:
步骤1:清理数据并过滤空行
在转换时间戳前,先对time列做字符串清理,去掉多余的空白字符(包括\r),同时过滤掉空行:
import requests import pandas as pd from datetime import datetime lat= 39 #Latitude lon=-4 #Longitude mountingplace = "building" angle=15 aspect = 0 url = "https://re.jrc.ec.europa.eu/api/seriescalc?lat={}&lon={}&outputformat=csv&browser=1&startyear=2015&endyear=2016&peakpower=1&mountingplace={}&angle={}&pvcalculation=1&aspect={}&loss=5".format(lat,lon,mountingplace,angle, aspect) # 去掉手动指定的lineterminator,让pandas自动适配换行格式,同时跳过空行 pv = pd.read_csv(url, delimiter=',', skiprows=10, skip_blank_lines=True) # 清理time列的所有空白字符(包括\r、空格等) pv['time'] = pv['time'].str.strip() # 过滤掉time列为空的行 pv = pv[pv['time'].notna() & (pv['time'] != '')] # 转换为时间戳 pv['time'] = pd.to_datetime(pv['time'], format="%Y%m%d:%H%M")
关键说明
- 移除
lineterminator='\n':pandas默认会自动识别\n、\r\n等多种换行格式,手动指定反而可能漏处理单独的\r。 str.strip():可以彻底清除字符串首尾的所有空白字符(包括回车符、空格、制表符等)。- 过滤空行:通过
pv['time'].notna() & (pv['time'] != '')确保只处理有效的时间字符串。
内容的提问来源于stack exchange,提问作者Homer
相关产品推荐
相关产品推荐

