Daniel YC Lin
Daniel YC Lin

Reputation: 16032

How to convert DataFrame's DateTime element to Int64 milliseconds in Julia?

using TimeSeries, DataFrames
s="DateTime,Open,High,Low,Close,Volume
2020/01/05 16:14:01,20,23,19,20,30
2020/01/05 16:14:11,23,27,19,22,20
2020/01/05 17:14:01,24,28,19,23,10
2020/01/05 18:14:01,25,29,20,24,40
2020/01/06 08:02:01,26,30,22,25,50"
ta=readtimearray(IOBuffer(s),format="yyyy/mm/dd HH:MM:SS")
df = DataFrame(ta)
df.ms = Dates.millisecond.(df.timestamp)
df

the output result is strange, every ms is just zero?

5×7 DataFrame
│ Row │ timestamp           │ Open    │ High    │ Low     │ Close   │ Volume  │ ms    │
│     │ DateTime            │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ Int64 │
├─────┼─────────────────────┼─────────┼─────────┼─────────┼─────────┼─────────┼───────┤
│ 1   │ 2020-01-05T16:14:01 │ 20.0    │ 23.0    │ 19.0    │ 20.0    │ 30.0    │ 0     │
│ 2   │ 2020-01-05T16:14:11 │ 23.0    │ 27.0    │ 19.0    │ 22.0    │ 20.0    │ 0     │
│ 3   │ 2020-01-05T17:14:01 │ 24.0    │ 28.0    │ 19.0    │ 23.0    │ 10.0    │ 0     │
│ 4   │ 2020-01-05T18:14:01 │ 25.0    │ 29.0    │ 20.0    │ 24.0    │ 40.0    │ 0     │
│ 5   │ 2020-01-06T08:02:01 │ 26.0    │ 30.0    │ 22.0    │ 25.0    │ 50.0    │ 0     │

Upvotes: 2

Views: 1441

Answers (2)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42234

df.ms = Dates.value.(df.timestamp)

Dates.millisecond is returning the millisecond part of datetime.

Note that Julia is using 0000-01-01T00:00:00 as the epoch rather than the standard Unix epoch. One way to get the Unix epoch would be Int.(Dates.datetime2unix.(Dates.DateTime.(df.timestamp)))

Upvotes: 3

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69939

Use Dates.value.(df.timestamp). As you have a vector of DateTime values it will give you the number of milliseconds. If you had a Date object (date only, without time) you would get a number of days view Dates.value.

Upvotes: 1

Related Questions