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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:41:10