You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在gnuplot写入表格时按格式化时间筛选数据?

使用Gnuplot筛选指定时间范围的CSV数据并输出

我尝试了gnuplot中的xdata、xrange等多种格式组合,但始终无法实现需求:我有一个wind.csv文件(示例数据见下文),希望对数据进行处理后写入文件,但仅保留特定起止时间范围内的数据。不想使用awk或其他外部系统工具。

现有代码

reset session
set datafile separator ","
fmt = '%Y-%m-%d %H:%M:%S'
START=strptime(fmt, "1975-08-14 00:00:00")
END=strptime(fmt, "1975-08-15 00:00:00")
set table "outfile.dat"
plot "wind_.csv" using 3:2:0:(sprintf(strftime(fmt ,timecolumn(1,fmt)))) with table if (($1 > START) && ($1 < END))
unset table

示例数据

date,wind_speed,wind_direction
1975-08-13 22:00:00,4.1,23.0
1975-08-13 23:00:00,3.1,59.0
1975-08-14 00:00:00,5.2,30.0
1975-08-14 01:00:00,2.0,70.0
1975-08-14 02:00:00,5.7,87.0
1975-08-14 03:00:00,5.6,105.0
1975-08-14 04:00:00,5.8,116.0
1975-08-14 05:00:00,5.0,116.0
1975-08-14 06:00:00,4.5,123.0
1975-08-14 07:00:00,4.1,137.0
1975-08-14 08:00:00,3.6,151.0
1975-08-14 09:00:00,3.5,153.0
1975-08-14 10:00:00,3.5,180.0
1975-08-14 11:00:00,2.8,189.0
1975-08-14 12:00:00,1.7,183.0
1975-08-14 13:00:00,0.7,172.0
1975-08-14 14:00:00,0.4,252.0
1975-08-14 15:00:00,0.2,325.0
1975-08-14 16:00:00,0.6,53.0
1975-08-14 17:00:00,1.0,37.0
1975-08-14 18:00:00,0.7,73.0
1975-08-14 19:00:00,0.8,26.0
1975-08-14 20:00:00,1.8,56.0
1975-08-14 21:00:00,2.3,64.0
1975-08-14 22:00:00,1.9,67.0
1975-08-14 23:00:00,3.1,12.0
1975-08-15 00:00:00,2.8,73.0
1975-08-15 01:00:00,2.5,66.0
1975-08-15 02:00:00,3.0,83.0
1975-08-15 03:00:00,3.9,109.0
1975-08-15 04:00:00,3.9,109.0
1975-08-15 05:00:00,4.2,127.0
1975-08-15 06:00:00,3.6,146.0

修正后的代码

原代码的核心问题是直接用字符串格式的日期($1)和时间戳格式的START/END比较,这是无效的。需要先将日期字符串转换为时间戳,同时跳过表头行避免错误。以下是修正后的代码:

reset session
set datafile separator ","
fmt = '%Y-%m-%d %H:%M:%S'
START = strptime(fmt, "1975-08-14 00:00:00")
END = strptime(fmt, "1975-08-15 00:00:00")

# 跳过CSV表头行
set datafile skip 1

set table "outfile.dat"
# 转换日期为时间戳,判断范围后输出原始日期、风速、风向
plot "wind.csv" using \
    (strftime(fmt, timecolumn(1,fmt))):2:3 \
    with table \
    if (timecolumn(1,fmt) >= START && timecolumn(1,fmt) < END)
unset table

关键修改说明

  • 使用timecolumn(1,fmt)将第一列的日期字符串转换为时间戳,才能和START/END的时间戳数值进行比较
  • 添加set datafile skip 1跳过CSV的表头行,避免处理非数据内容
  • 调整using语句,输出需要的列(日期、风速、风向),保证输出格式符合需求

内容的提问来源于stack exchange,提问作者MathX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 21:17:16