使用AWS Wrangler Athena API在Glue中读取数据遇AttributeError求助
解决Glue中使用AWS Wrangler读取Athena date类型列的AttributeError问题
问题场景
我在Athena中有一张表,所有列的数据类型配置正确(date、bigint、int、decimal(28,2)、string等),其中date列格式为'YYYY-MM-DD'。在Glue中使用AWS Wrangler的athena.read_sql_query API读取数据时,执行代码:
athena.read_sql_query(sql=test_query, database=test_db, ctas_approach=False)
出现错误:AttributeError: Can only use .dt accessor with datetimelike values,需要保留原始数据类型,不想全部转为varchar。
解决方案
修改ctas_approach参数为True,必要时可指定临时数据存储的S3路径,修改后的代码如下:
import awswrangler as wr # 可选:自定义临时数据存储的S3路径,若无指定则使用默认临时桶 temp_s3_location = "s3://your-custom-temp-bucket/athena-temp-data/" df = wr.athena.read_sql_query( sql=test_query, database=test_db, ctas_approach=True, s3_output=temp_s3_location # 可选参数 )
原因说明
当ctas_approach=False时,AWS Wrangler直接读取Athena查询的文本结果,在Glue环境下这种方式会将date类型列解析为字符串,而非pandas可识别的datetime/date类型,导致.dt访问器调用失败。
开启ctas_approach=True后,Wrangler会通过CTAS语句创建一个临时的Parquet格式表,Parquet作为列式存储格式能精准保留Athena的原始数据类型,读取后的DataFrame中date列会被正确解析为datetime64类型,即可正常使用.dt相关操作,同时其他数据类型(如decimal、bigint)也能完整保留。
注意事项
- 确保Glue执行角色拥有指定临时S3路径的读写权限
- 临时表和对应数据默认会在24小时后自动清理,可通过
ctas_temp_table_ttl参数调整保留时长
内容的提问来源于stack exchange,提问作者zac yang
相关产品推荐
相关产品推荐

