如何使用内联命令向Kusto表插入当前时间戳?
在Kusto中插入当前时间戳的可行方法
当内联插入命令(如.insert inline)不支持直接使用now()函数时,你可以通过以下几种方式实现需求:
1. 客户端预计算时间戳
在发起插入请求前,先用客户端脚本(如PowerShell、Python)获取当前UTC时间,再将计算后的时间值传入插入语句。
示例(PowerShell):
$currentUtcTime = Get-Date -Utc -Format "yyyy-MM-ddTHH:mm:ss.fffffffZ" az data explorer query --cluster "your-cluster.kusto.windows.net" --database "your-db" --query ".insert into YourTable (Timestamp, Data) values ('$currentUtcTime', 'sample-data')"
示例(Python):
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder from datetime import datetime cluster = "https://your-cluster.kusto.windows.net" client = KustoClient(KustoConnectionStringBuilder.with_aad_device_authentication(cluster)) current_time = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ") query = f".insert into YourTable (Timestamp, Data) values ('{current_time}', 'sample-data')" client.execute_mgmt("your-db", query)
2. 使用.set/.append结合查询语句
Kusto的.set(覆盖表)或.append(追加数据)命令支持通过查询语句生成数据,这时候可以直接使用now()函数。
追加数据示例:
.append YourTable <| datatable(Timestamp:datetime, Data:string) [ now(), "sample-data-1", now(), "sample-data-2" ]
覆盖表数据示例(谨慎使用,会清空原有数据):
.set YourTable <| datatable(Timestamp:datetime, Data:string) [ now(), "sample-data" ]
3. 为表列设置默认值
如果你的表需要每次插入自动填充当前时间戳,可以在创建表时为Timestamp列指定默认值为now(),之后插入数据时无需显式提供该列的值。
创建带默认值的表:
.create table YourTable ( Timestamp:datetime default now(), Data:string )
插入数据时省略Timestamp列:
.insert into YourTable (Data) values ("sample-data")
此时Timestamp列会自动填充插入操作时的当前UTC时间。
内容的提问来源于stack exchange,提问作者Swathi Miney
相关产品推荐
相关产品推荐

