【问题标题】:PySpark date_trunc modifies the timezone: how to prevent it?PySpark date_trunc 修改时区:如何防止?
【发布时间】:2020-05-07 06:39:32
【问题描述】:

上下文:我使用从 pyspark.sql.functions 导入的 date_trunc 函数将时间戳截断为分钟。

df_truncated = df.withColumn('dt', date_trunc('minute', df["timestamp"]))
df_truncated.show(truncate=False)

输出如下

+------------------------+-------------------+
|timestamp               |dt                 |
+------------------------+-------------------+
|2020-01-02T00:30:47.178Z|2020-01-02 02:30:00|
|2020-01-02T00:30:47.160Z|2020-01-02 02:30:00|
|2020-01-02T00:30:46.327Z|2020-01-02 02:30:00|
|2020-01-02T00:30:45.003Z|2020-01-02 02:30:00|
|2020-01-02T00:30:44.054Z|2020-01-02 02:30:00|
+------------------------+-------------------+

问题:问题是它“增加”了两个小时到原始 timstamp - 从 utc 转换为本地时间。

问题:我怎样才能避免这种情况?我是否需要手动截断时间戳或 date_trunc 函数的某些参数未记录?或者我是否需要访问 spark 全局设置,如果需要,那么如何或哪些设置?

【问题讨论】:

    标签: date pyspark timestamp timezone truncation


    【解决方案1】:

    你可以试试这个并告诉我。

    ##  Here i am selecting the substring of the column "timestamp". Choose everthing till the seconds and convert that to a timestamp.
    
    df.withColumn("hour", F.to_timestamp(F.substring("timestamp_value", 0, 19), "yyyy-MM-dd'T'HH:mm:ss")).show()
    
    +-------------------------+-------------------+
    |timestamp                |hour               |
    +-------------------------+-------------------+
    |2017-08-01T14:30:00+05:30|2017-08-01 14:30:00|
    |2017-08-01T14:30:00+06:30|2017-08-01 14:30:00|
    |2017-08-01T14:30:00+07:30|2017-08-01 14:30:00|
    +-------------------------+-------------------+
    

    更多技术可以参考链接:Link

    【讨论】:

    • 所以这属于“手动”方法。当我尝试使用 to_timestamp 函数时,格式参数有问题,所以谢谢你。稍作修改以将时间戳缩短为分钟:df.withColumn("hour", F.date_trunc('minute',F.to_timestamp(F.substring("timestamp", 0, 19), "yyyy-MM-dd'T'HH:mm:ss"))).show()
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 2013-06-14
    • 2022-01-20
    • 1970-01-01
    • 2013-12-11
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多