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

如何在AWS Athena中将指定日期格式转换为epoch_utc及epoch_utc_tz?

Athena SQL 日期转Epoch时间 + 筛选订单最新条目方案

一、将带时区的日期转成Epoch时间

你的日期格式是标准ISO 8601带UTC时区格式(2023-03-19T00:19:47+00:00),Athena基于Presto语法,用内置函数就能快速完成转换:

1. 转UTC时间戳(epoch_utc,从1970-01-01 UTC开始的秒数)

直接把字符串类型的日期字段转为TIMESTAMP WITH TIME ZONE,再用to_unixtime()提取秒数:

SELECT
  order_id,
  created_date,
  updated_date,
  -- 转换created_date为UTC epoch秒数
  to_unixtime(cast(created_date AS TIMESTAMP WITH TIME ZONE)) AS epoch_utc_created,
  -- 转换updated_date为UTC epoch秒数
  to_unixtime(cast(updated_date AS TIMESTAMP WITH TIME ZONE)) AS epoch_utc_updated
FROM 你的客户表名;

2. 转指定时区的Epoch时间(epoch_utc_tz)

如果需要转成其他时区(比如东八区Asia/Shanghai)对应的Epoch秒数,可先转时区再提取:

SELECT
  order_id,
  updated_date,
  -- 将UTC时间转成东八区后,再转成Epoch秒数
  to_unixtime(cast(updated_date AS TIMESTAMP WITH TIME ZONE) AT TIME ZONE 'Asia/Shanghai') AS epoch_utc_tz_updated
FROM 你的客户表名;

二、筛选每个订单的最新条目

要找到同一order_id下updated_date最新的记录,不用转Epoch也能直接比较,用窗口函数row_number()更高效:

WITH ranked_orders AS (
  SELECT
    *,
    row_number() OVER (
      PARTITION BY order_id 
      ORDER BY cast(updated_date AS TIMESTAMP WITH TIME ZONE) DESC
    ) AS rn
  FROM 你的客户表名
)
SELECT *
FROM ranked_orders
WHERE rn = 1;

如果一定要用Epoch时间排序,也可以把ORDER BY换成对应的Epoch字段:

WITH ranked_orders AS (
  SELECT
    *,
    to_unixtime(cast(updated_date AS TIMESTAMP WITH TIME ZONE)) AS epoch_utc_updated,
    row_number() OVER (
      PARTITION BY order_id 
      ORDER BY to_unixtime(cast(updated_date AS TIMESTAMP WITH TIME ZONE)) DESC
    ) AS rn
  FROM 你的客户表名
)
SELECT *
FROM ranked_orders
WHERE rn = 1;

注意事项

  • 如果created_date和updated_date已经是TIMESTAMP WITH TIME ZONE类型,直接用to_unixtime()即可,无需额外cast。
  • 时区参数建议用Presto支持的时区名称(如Asia/Shanghai、America/New_York),比偏移量格式(如+8:00)更稳妥。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:55:35