len*_*ehm 5 python timestamp unix-timestamp dataframe pyspark
我的数据帧时间戳中有一列中有一个列,其中包含 UNIX 13 位时间戳,如下所示:
| 时间戳| | ------------- | | 1584528257638 | | 1586618807677 | | 1585923477767 | | 1583314882085 |
使用 pandas 可以很容易地将其转换为:
ms = pd.to_datetime(df[column], unit='ms')
df[column] = ms
Run Code Online (Sandbox Code Playgroud)
然而,在 pySpark 中,这并不那么容易,我发现了其他一些内容,例如这篇文章试图实现这个目标。最后毫秒的串联对我不起作用,它总是导致第二个时间戳 (HH:mm:ss) 而不是 HH:mm:ss.SSS。
到目前为止我尝试过的是:
df = df.withColumn("unix_timestamp", F.unix_timestamp(df.timestamp,'yyyy-MM-dd HH:mm:ss.SSS z') + F.substring(df.timestamp, -3,3).cast('float')/1000)
df = df.withColumn("ms_Timestamp", F.to_timestamp(df["unix_timestamp"]))
Run Code Online (Sandbox Code Playgroud)
不幸的是,没有将其转换为毫秒时间戳,我不知道还能做什么。
我将不胜感激最终获得毫秒时间戳的任何帮助。
祝一切顺利,并提前致谢。
默认to_timestamp, from_unixtime, unix_timestamp
函数不会产生毫秒。
但要获得解决方法,请使用from_unixtime
和concat
函数来获取以毫秒为单位的时间戳。
#using substring function
df.withColumn("unix_timestamp", concat_ws(".",from_unixtime(substring(col("timestamp"),0,10),"yyyy-MM-dd HH:mm:ss"),substring(col("timestamp"),-3,3))).show(10,False)
#using divide function
df.withColumn("unix_timestamp", concat_ws(".",from_unixtime((col("timestamp")/1000),"yyyy-MM-dd HH:mm:ss"),substring(col("timestamp"),-3,3))).show(10,False)
#+-------------+-----------------------+
#|timestamp |unix_timestamp |
#+-------------+-----------------------+
#|1584528257638|2020-03-18 05:44:17.638|
#|1586618807677|2020-04-11 10:26:47.677|
#|1585923477767|2020-04-03 09:17:57.767|
#|1583314882085|2020-03-04 03:41:22.085|
#+-------------+-----------------------+
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3254 次 |
最近记录: |