TDengine使用Node.js连接器查询时timestamp丢失毫秒精度如何解决
TDengine Node.js连接器时间戳毫秒丢失问题解决方案
问题原因
你使用的td2.0-connector连接器默认将TDengine的timestamp类型字段序列化为精确到秒的格式化字符串,毫秒部分默认不会包含在返回结果中,因此用Date.parse转换时会丢失毫秒精度。
解决方案
方案1(推荐):配置返回毫秒级时间戳数值
在连接配置中新增fetchTimestampAsNumber: true参数,让连接器直接返回13位毫秒时间戳数值,无需额外格式转换:
const taos = require('td2.0-connector'); var host = "127.0.0.1"; var port = 6030; var conn = taos.connect({ host: host, user: "root", password: "taosdata", port: port, // 新增配置项,指定时间戳返回为毫秒数值 fetchTimestampAsNumber: true }); var cursor = conn.cursor(); cursor.execute('create database if not exists demo'); cursor.execute('use demo'); cursor.execute('create table if not exists t1 (ts timestamp, _int int);'); cursor.execute('insert into t1 values(1627894963923, 0)'); cursor.execute('select * from t1'); cursor.fetchall(); // 直接读取数值即可,无需Date.parse转换 console.log(cursor.data[0][0]); // 输出1627894963923
方案2:保留字符串格式,新增毫秒位格式化规则
如果需要保留时间字符串的返回格式,在连接配置中指定时间格式化规则,明确带上毫秒位:
var conn = taos.connect({ host: host, user: "root", password: "taosdata", port: port, // 配置时间格式包含毫秒 timestampFormat: 'YYYY-MM-DD HH:mm:ss.SSS' });
配置完成后,cursor.data[0][0]返回的字符串会携带毫秒信息,Date.parse(cursor.data[0][0])即可得到完整的13位毫秒时间戳。
内容的提问来源于stack exchange,提问作者Jackson
相关产品推荐
相关产品推荐

