

# 使用日期和时间进行查询
<a name="query-examples-waf-logs-date-time"></a>

本部分中的示例包括使用日期和时间值的查询。
+ [Return the timestamp field in human-readable ISO 8601 format](#waf-example-return-human-readable-timestamp)
+ [Return records from the last 24 hours](#waf-example-return-records-last-24-hours)
+ [Return records for a specified date range and IP address](#waf-example-return-records-date-range-and-ip)
+ [For a specified date range, count the number of IP addresses in five minute intervals](#waf-example-count-ip-addresses-in-date-range)
+ [Count the number of X-Forwarded-For IP in the last 10 days](#waf-example-count-x-forwarded-for-ip)

**Example – 以人类可读 ISO 8601 格式返回时间戳字段**  
以下查询使用 `from_unixtime` 和 `to_iso8601` 函数以人类可读的 ISO 8601 格式返回 `timestamp` 字段（例如 `2019-12-13T23:40:12.000Z` 而不是 `1576280412771`）。该查询还返回 HTTP 源名称、源 ID 和请求。  

```
SELECT to_iso8601(from_unixtime(timestamp / 1000)) as time_ISO_8601,
       httpsourcename,
       httpsourceid,
       httprequest
FROM waf_logs
LIMIT 10;
```

**Example – 返回过去 24 小时的记录**  
以下查询使用 `WHERE` 子句中的筛选条件返回过去 24 小时内记录的 HTTP 源名称、HTTP 源 ID 和 HTTP 请求字段。  

```
SELECT to_iso8601(from_unixtime(timestamp/1000)) AS time_ISO_8601, 
       httpsourcename, 
       httpsourceid, 
       httprequest 
FROM waf_logs
WHERE from_unixtime(timestamp/1000) > now() - interval '1' day
LIMIT 10;
```

**Example – 返回指定日期范围和 IP 地址的记录**  
以下查询列出了指定的客户端 IP 地址在指定日期范围内的记录。  

```
SELECT * 
FROM waf_logs 
WHERE httprequest.clientip='53.21.198.66' AND "date" >= '2021/03/01' AND "date" < '2021/03/31'
```

**Example – 对于指定的日期范围，计算在五分钟间隔内的 IP 地址数**  
对于特定日期范围，以下查询计算在五分钟间隔内的 IP 地址数。  

```
WITH test_dataset AS 
  (SELECT 
     format_datetime(from_unixtime((timestamp/1000) - ((minute(from_unixtime(timestamp / 1000))%5) * 60)),'yyyy-MM-dd HH:mm') AS five_minutes_ts,
     "httprequest"."clientip" 
     FROM waf_logs 
     WHERE "date" >= '2021/03/01' AND "date" < '2021/03/31')
SELECT five_minutes_ts,"clientip",count(*) ip_count 
FROM test_dataset 
GROUP BY five_minutes_ts,"clientip"
```

**Example – 计算过去 10 天内 X-Forwarded-For IP 的数量**  
以下查询将筛选请求标头，并统计过去 10 天内 X-Forwarded-For IP 的数量。  

```
WITH test_dataset AS
  (SELECT header
   FROM waf_logs
   CROSS JOIN UNNEST (httprequest.headers) AS t(header)
   WHERE from_unixtime("timestamp"/1000) > now() - interval '10' DAY) 
SELECT header.value AS ip,
       count(*) AS COUNT 
FROM test_dataset 
WHERE header.name='X-Forwarded-For' 
GROUP BY header.value 
ORDER BY COUNT DESC
```

有关日期和时间函数的更多信息，请参阅 Trino 文档中的 [日期与时间函数和运算符](https://trino.io/docs/current/functions/datetime.html)。