如何使用Pandas将特定格式的日期时间列转为datetime类型?
解决Pandas中按空格分隔的年-年内天数-小时转datetime格式的问题
问题描述
我有一个DataFrame,其中“Date and Time”列的格式为年份 年内第几天 一天中的小时数,例如第一行值为1969 58 0。尝试了以下代码转换为datetime格式但均失败:
df['Date and Time']= pd.to_datetime(df["Date and Time"], format = "%YYYY%DDD%H")
df['Date and Time']= pd.to_datetime(df["Date and Time"], format = "%Y%DDD%H")
df['Date and Time']= pd.to_datetime(df["Date and Time"], format = "%Y%j%H")
解决方案
你的核心问题是格式字符串没有匹配原始数据的空格分隔符,同时部分格式码使用错误:
%j是Pandas中代表「年内第几天」的正确格式码(支持1-3位数字,无需手动补零)- 原始数据是空格分隔的三个部分,格式字符串必须对应加入空格
正确的转换代码如下:
df['Date and Time'] = pd.to_datetime(df["Date and Time"], format="%Y %j %H")
验证示例
运行以下测试代码可以确认效果:
import pandas as pd test_data = pd.DataFrame({"Date and Time": ["1969 58 0"]}) test_data['Date and Time'] = pd.to_datetime(test_data["Date and Time"], format="%Y %j %H") print(test_data['Date and Time']) # 输出:0 1969-02-27 00:00:00 # Name: Date and Time, dtype: datetime64[ns]
如果你的数据中存在天数不足3位的情况(比如58而非058),%j会自动识别并转换,无需额外补零操作。
内容的提问来源于stack exchange,提问作者Oscar Batalla
相关产品推荐
相关产品推荐

