Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PySpark-使用本机Spark函数将长历元(以毫秒为单位)强制转换为TimestampType_Python_Apache Spark_Pyspark_Timestamp - Fatal编程技术网

Python PySpark-使用本机Spark函数将长历元(以毫秒为单位)强制转换为TimestampType

Python PySpark-使用本机Spark函数将长历元(以毫秒为单位)强制转换为TimestampType,python,apache-spark,pyspark,timestamp,Python,Apache Spark,Pyspark,Timestamp,我正在使用PySpark库读取JSON文件,处理数据,然后写回拼花地板文件 传入数据有一个从历元开始测量的日期字段(以毫秒为单位)。例如,1541106106796表示:2018年11月1日星期四9:01:46.796 PM 有效的解决方案使用Pythondatetime库: def format_datetime(ts): return datetime.fromtimestamp(ts/1000.0) ... get_timestamp = udf(lambda x: format

我正在使用PySpark库读取JSON文件,处理数据,然后写回拼花地板文件

传入数据有一个从历元开始测量的日期字段(以毫秒为单位)。例如,
1541106106796
表示:
2018年11月1日星期四9:01:46.796 PM

有效的解决方案使用Python
datetime
库:

def format_datetime(ts):
    return datetime.fromtimestamp(ts/1000.0)

...
get_timestamp = udf(lambda x: format_datetime(int(x)),TimestampType())
df = df.withColumn("timestamp", get_timestamp(df.ts))

是否有只使用本机Spark函数的解决方案?

使用unixtime中的
,并从时间戳中提取毫秒,然后在末尾添加,最后转换为
时间戳
类型

df.show()
#+-------------+
#|           ts|
#+-------------+
#|1541106106796|
#+-------------+

df.withColumn("ts1",expr('concat_ws(".",from_unixtime(substring(ts,1,length(ts)-3),"yyyy-MM-dd HH:mm:ss"),substring(ts,length(ts)-2,length(ts)))').cast("timestamp")).\
show(10,False)
#+-------------+-----------------------+
#|ts           |ts1                    |
#+-------------+-----------------------+
#|1541106106796|2018-11-01 16:01:46.796|
#+-------------+-----------------------+
要创建
unixtime
请使用
unix\u时间戳
regexp\u extract
函数

示例:

df.show(10,False)
#+-----------------------------------------+
#|sample                                   |
#+-----------------------------------------+
#|Thursday, November 1, 2018 9:01:46.796 PM|
#+-----------------------------------------+

df.withColumn("ts",concat_ws('',unix_timestamp(col("sample"),"E, MMMM d, yyyy hh:mm:ss.SSS a"),regexp_extract(col("sample"),"\\.(.*)\\s+",1))).\
show(10,False)
#+-----------------------------------------+-------------+
#|sample                                   |ts           |
#+-----------------------------------------+-------------+
#|Thursday, November 1, 2018 9:01:46.796 PM|1541124106796|
#+-----------------------------------------+-------------+