Home > OS >  How to convert epoch/unix time in Julia dataframe?
How to convert epoch/unix time in Julia dataframe?

Time:10-15

I am trying to find solution to convert df[!, r"TimeStamp"] , which is unix or epoch time, to datetime format with plus 9 hours, such as pd.to_datetime(df["TimeStamp"], unit = "ms") in Python.

Here example of Julia dataframe :

df = DataFrame(TimeStamp = [1632868171713,1632868172713,1632868173713], 
               Roll = [-1.1, -2, 1],
               Pitch =[-1, -1, 3.1],
               Yaw = [-1, -4.2, 2],
               )

and, below is expected output.

    TimeStamp                  Roll     Pitch   Yaw
    Date                       Float64  Float64 Float64
1   2021-09-29 07:29:31.713    -1.1     -1.0    -1.0
2   2021-09-29 07:29:32.713    -2.0     -1.0    -4.2
3   2021-09-29 07:29:33.713     1.0      3.1    2.0

Update:

I have solution with unix2datetime() with using for loops, with @ MrFuppes helps, but wonder if there is function like pd.to_datetime and timedelta(hours = 9) in Julia.

CodePudding user response:

you could broadcast the timestamp column to DateTime. Adding a duration is also pretty straight forward:

using Dates
using DataFrames

df = DataFrame(TimeStamp=[1632868171713,1632868172713,1632868173713],
               Roll=[-1.1, -2, 1],
               Pitch=[-1, -1, 3.1],
               Yaw=[-1, -4.2, 2],
               )

df.Date = unix2datetime.(df.TimeStamp / 1000)

# or map it:
# df.Date = map(unix2datetime, df.TimeStamp / 1000)

df.DatePlusSevenH = df.Date   Hour(7)

println(df)

# 3×6 DataFrame
#  Row │ TimeStamp      Roll     Pitch    Yaw      Date                     DatePlusSevenH
#      │ Int64          Float64  Float64  Float64  DateTime                 DateTime
# ─────┼────────────────────────────────────────────────────────────────────────────────────────────
#    1 │ 1632868171713     -1.1     -1.0     -1.0  2021-09-28T22:29:31.713  2021-09-29T05:29:31.713 
#    2 │ 1632868172713     -2.0     -1.0     -4.2  2021-09-28T22:29:32.713  2021-09-29T05:29:32.713 
#    3 │ 1632868173713      1.0      3.1      2.0  2021-09-28T22:29:33.713  2021-09-29T05:29:33.713 

  • Related