使用Pandas读取CSV时将指定列转为datetime.date类型的方法
解决CSV读取时将日期列转为datetime.date类型的问题
嘿,这个需求我刚好处理过,给你两个简便的方法直接在读取CSV时把col4转换成datetime.date类型,完美匹配你要和SQL返回值对比的场景:
方法一:使用converters参数自定义转换函数
这是最直接的方式,在pd.read_csv里通过converters指定针对col4的转换逻辑,直接输出date对象:
from datetime import datetime # 定义字符串转date的函数 def str_to_date(date_str): return datetime.strptime(date_str, '%Y-%m-%d').date() headers = ['col1', 'col2', 'col3', 'col4','col5','col6'] dtypes = {'col1': 'int', 'col2': 'str', 'col3': 'str', 'col4': 'str','col5': 'str','col6': 'int'} test = pd.read_csv( "solution.csv", sep=',', header=None, names=headers, dtype=dtypes, converters={'col4': str_to_date} # 指定col4的转换函数 )
这样读取后,test['col4']的每一个值都是datetime.date类型,打印test.values就能得到你想要的格式:
array([[107, 'Berg Live', 'Berg', datetime.date(2017, 1, 8), 'Concert', 7]], dtype=object)
方法二:读取后批量转换(备选方案)
如果不想在读取时处理,也可以先读取为Timestamp,再批量转成date:
test = pd.read_csv("solution.csv", sep=',', header=None, names=headers, dtype=dtypes) test['col4'] = pd.to_datetime(test['col4']).dt.date
不过这个方法需要多一步后续处理,不如第一种高效。
顺便提一下:你之前用的date_parser参数之所以没得到date对象,是因为pd.to_datetime默认返回的是Timestamp类型,必须自定义转换逻辑才能输出datetime.date。
内容的提问来源于stack exchange,提问作者Roby
相关产品推荐
相关产品推荐

