Windows平台下C++读取Parquet文件timestamp字段方法咨询
在Windows C++中正确读取Parquet的Timestamp列
核心原理
Parquet中的timestamp列底层以int64类型存储Unix时间戳,精度通常为纳秒或微秒(取决于文件定义)。你当前读取到的1671205687722819000是纳秒级时间戳(从1970-01-01 00:00:00 UTC开始的纳秒数),需要转换为C++的时间类型再格式化。
步骤1:修正读取代码(避免溢出)
你当前用int存储时间戳会导致溢出,必须改为int64_t:
std::shared_ptr<parquet::RowGroupReader> row_group_1 = demoObj->myParquetReader->RowGroup(0); std::shared_ptr<parquet::ColumnReader> colVal = row_group_1->Column(4); // 先验证列的物理类型是否为INT64(Parquet timestamp底层是INT64) if (colVal->type()->physical_type() != parquet::Type::INT64) { // 处理类型不匹配的异常情况 return; } parquet::Int64Reader* readerVal = static_cast<parquet::Int64Reader*>(colVal.get()); int64_t timestamp_raw; // 存储原始时间戳 int rowsRead; int valRead; // 读取单条数据 rowsRead = readerVal->ReadBatch(1, nullptr, nullptr, ×tamp_raw, &valRead);
步骤2:转换为C++时间点并格式化
利用C++11的<chrono>库,将原始时间戳转换为可格式化的时间结构:
情况1:时间戳为纳秒精度(你的数据属于此情况)
#include <chrono> #include <ctime> #include <string> #include <iomanip> #include <sstream> // 将纳秒时间戳转换为system_clock时间点 auto time_point = std::chrono::time_point<std::chrono::system_clock>( std::chrono::nanoseconds(timestamp_raw) ); // 转换为UTC时间的tm结构 std::time_t time_t_val = std::chrono::system_clock::to_time_t(time_point); std::tm utc_tm = *std::gmtime(&time_t_val); // gmtime返回UTC时间,localtime返回本地时间 // 提取微秒部分(tm结构仅保留到秒,需单独提取小数部分) auto total_duration = time_point.time_since_epoch(); auto microseconds_part = std::chrono::duration_cast<std::chrono::microseconds>(total_duration) % 1000000; // 格式化为目标字符串:YYYY-MM-DD HH:MM:SS.ffffff+00:00 std::ostringstream oss; oss << std::put_time(&utc_tm, "%Y-%m-%d %H:%M:%S") << "." << std::setw(6) << std::setfill('0') << microseconds_part.count() << "+00:00"; std::string formatted_datetime = oss.str(); // 得到最终格式化后的时间字符串
情况2:时间戳为微秒精度
如果你的Parquet列是微秒精度(原始数值为1671205687722819),只需将std::chrono::nanoseconds替换为std::chrono::microseconds即可,后续格式化逻辑一致。
验证列精度的方法
可以用parquet-tools工具查看Parquet文件的schema,确认timestamp列的精度:
parquet-tools schema your_file.parquet
输出中会显示类似timestamp: INT64 (TIMESTAMP(NANOS))的信息,明确精度是纳秒还是微秒。
内容的提问来源于stack exchange,提问作者RKum
相关产品推荐
相关产品推荐

