IBM Watson传感器数据格式化求助:拆分时间戳及Node-RED实现
Hey there! Since you're working with Node-RED and need to split that combined timestamp into separate date and time fields for IBM Watson, here's a straightforward solution tailored to your setup.
Step 1: Use a Function Node for Custom Data Manipulation
The most flexible way to handle this in Node-RED is with a Function node—it lets you write simple JavaScript to split the timestamp exactly how you need it.
- Drag a Function node from the palette into your flow, connecting it right after the node that outputs your sensor JSON data.
Step 2: Paste This Code into the Function Node
// Adjust the path below if your timestamp is stored elsewhere (e.g., msg.timestamp) const rawTimestamp = msg.payload.timestamp; const timestamp = new Date(rawTimestamp); // Validate the timestamp to avoid errors downstream if (isNaN(timestamp.getTime())) { node.error(`Invalid timestamp format: ${rawTimestamp}`, msg); return null; // Stop processing if the timestamp can't be parsed } // Split into date and time (ISO 8601 format, which works great for Watson and visualization tools) msg.payload.date = timestamp.toISOString().split('T')[0]; // Outputs "YYYY-MM-DD" msg.payload.time = timestamp.toISOString().split('T')[1].split('.')[0]; // Outputs "HH:MM:SS" // Optional: Use locale-specific formats if needed // msg.payload.date = timestamp.toLocaleDateString(); // e.g., "10/5/2024" // msg.payload.time = timestamp.toLocaleTimeString(); // e.g., "14:30:45" // Optional: Remove the original timestamp if you don't need it anymore // delete msg.payload.timestamp; return msg;
Step 3: Configure and Test
- Update the
msg.payload.timestamppath to match where your actual timestamp lives in your JSON payload. For example, if it's stored directly inmsg.timestamp, change the first line toconst rawTimestamp = msg.timestamp;. - Deploy your flow, send a test payload with your combined timestamp, and check the output. You’ll see new
dateandtimefields in your payload, ready to send to IBM Watson.
Alternative: No-Code Option with JSONata in a Change Node
If you prefer avoiding code, use a Change node with JSONata expressions:
- Add a Change node to your flow.
- Add a "Set" action:
- Target:
msg.payload.date - Value:
$split($formatDateTime($toMillis(msg.payload.timestamp), "yyyy-MM-dd'T'HH:mm:ss"), "T")[0]
- Target:
- Add a second "Set" action:
- Target:
msg.payload.time - Value:
$split($formatDateTime($toMillis(msg.payload.timestamp), "yyyy-MM-dd'T'HH:mm:ss"), "T")[1]
- Target:
Key Notes
- Make sure your timestamp is in a format JavaScript’s
Date()constructor can parse (e.g., ISO 8601 like "2024-10-05T14:30:45Z" or a Unix timestamp). If it’s a non-standard string, you’ll need to tweak the parsing logic slightly. - The ISO 8601 date/time format we used is ideal for IBM Watson and most data visualization tools, as it’s universally recognized and avoids formatting conflicts.
内容的提问来源于stack exchange,提问作者user7499377
相关产品推荐
相关产品推荐

