Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - How to convert a numeric type column into timestamp column?

I have sample records as looks below and I want to convert the Time numeric column (Which represents milliseconds value) into the timestamp column.

Value   Time
0.00346 0
0.01584 0.002
0.00621 0.004
.....
.....
.....
0.00204 0.998
0.00617 1
0.00204 1.002

Let's take HH:mm:ss.SSS is the timestamp format and the output should be as below

Value   Time   timestamp
0.00346 0      00:00:00.000
0.01584 0.002  00:00:00.002
0.00621 0.004  00:00:00.004
.....          ........
.....          ........
.....          ........
0.00204 0.998  00:00:00.998
0.00617 1      00:00:01.000
0.00204 1.002  00:00:01.002
question from:https://stackoverflow.com/questions/65881353/how-to-convert-a-numeric-type-column-into-timestamp-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can cast the column to timestamp type and then use date_format to convert to the desired format:

import pyspark.sql.functions as F

df2 = df.withColumn('timestamp', F.date_format(F.col('Time').cast('timestamp'), 'HH:mm:ss.SSS'))

df2.show()
+-------+-----+------------+
|  Value| Time|   timestamp|
+-------+-----+------------+
|0.00346|  0.0|00:00:00.000|
|0.01584|0.002|00:00:00.002|
|0.00621|0.004|00:00:00.004|
|0.00204|0.998|00:00:00.998|
|0.00617|  1.0|00:00:01.000|
|0.00204|1.002|00:00:01.002|
+-------+-----+------------+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...