【问题标题】:How to convert int (yyyymmdd) to timestamp in SQL?如何在 SQL 中将 int (yyyymmdd) 转换为时间戳?
【发布时间】:2019-07-01 01:19:09
【问题描述】:

我正在使用 Redshift,并且在表格中有一个字段作为 int 类型表示一天的日期。例如 int 是 20180215 。格式为 yyyymmdd。

我想知道使用 SQL 将此 int 转换为时间戳 (yyyy-mm-dd hh:mm:ss) 的最有效方法是什么。

【问题讨论】:

    标签: sql postgresql hive amazon-redshift


    【解决方案1】:

    使用to_timestamp().

    select to_timestamp(20180215::text, 'YYYYMMDD')::timestamp
    
        to_timestamp     
    ---------------------
     2018-02-15 00:00:00
    (1 row)
    

    函数返回timestamp with time zone。结果取决于当前时区设置。您可以将结果转换为 timestamp 以跳过时区部分。

    【讨论】:

    • 如果输入的是一个int,那么先把它转成字符串做上面的事情,如:select to_timestamp(col1::TEXT, 'YYYYMMDD');
    • 谢谢。如果我将 int 转换为字符串,然后再转换为时间戳,您是否看到任何性能下降?我将对数十亿条记录执行此操作,并对最佳 sql 感兴趣
    • @codeshark 会产生影响,但与从磁盘读取相比非常快。如果您打算将日期用作日期,那么最好在 ETL 过程中将数据直接导入日期字段。
    • 谢谢。另外,如何确保时间戳是UTC?例如 20180215 应该创建时间戳 2018-02-15 00:00:00
    【解决方案2】:

    我认为这是最好的

    import datetime
    date_format = "%Y%m%d"
    timestamp = datetime.datetime.strptime("20180215", date_format).timestamp()
    timestamp
    # 1518620400.0
    

    你可以通过制作函数来改善它

    def date_2_timestamp(date):
        from datetime.datetime import strptime
        return strptime(date, "%Y%m%d").timestamp()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 2021-01-12
      • 1970-01-01
      • 2021-06-03
      相关资源
      最近更新 更多