9

I have a dataframe with timestamp values, like this one: 2018-02-15T11:39:13.000Z I want to have it in UNIX format, using Pyspark.

I tried something like data = datasample.withColumn('timestamp_cast', datasample['timestamp'].cast('date')) but I lose a lot of information, since I only get day/month/year when I have milliseconds information in my source.

Result: 2018-02-15

Any idea to get unix format and keep precision? Thank you!

Ticoincoin
  • 157
  • 1
  • 2
  • 15
  • 1
    You need to use [`pyspark.sql.functions.unixtimestamp`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.from_unixtime). – pault Nov 13 '18 at 16:22

2 Answers2

15

You can use the built in unix_timestamp the following ways:

from pyspark.sql.functions import unix_timestamp
df = df.withColumn('unix', unix_timestamp('timestamp'))

Or

df = df.selectExpr('unix_timestamp(timestamp)')
pault
  • 41,343
  • 15
  • 107
  • 149
Tanjin
  • 2,442
  • 1
  • 13
  • 20
0

Another possible method is to directly cast the column to integer

df.withColumn('timestamp_unix', F.col('timestamp').cast('int'))
Ric S
  • 9,073
  • 3
  • 25
  • 51