Get difference between two dates in seconds

Hi everyone,

I am currently encountering an issue regarding the dates management with Julia.
The case is that I have two dates, formated in a SQL-friendly date state and I would like to know the difference between them, in seconds.

Date 1 : 2018-06-13T04:40:49
Date 2 : 2018-06-13T04:47:12

I tried to convert these dates in supported dates, but I have now to manage with milliseconds :

time_difference = Dates.DateTime(date2) - Dates.DateTime(date1)
println(time_difference)
383000 milliseconds

I cannot convert this milliseconds result into a seconds or hours results since I cannot perform a *() function on it :

time_difference = (Dates.DateTime(date2) - Dates.DateTime(date1) * 1000)
println(time_difference)
ERROR: LoadError: MethodError: no method matching *(::DateTime, ::Int64)

Would you have any method regarding this point ? In addition, how could we get the timestamp related to these two dates ? Since this is about seconds, we could then substract one to the other to get the seconds between them.

Thanks in advance for your help!

Finally found !

time_difference = Int(convert(Dates.Second, (Dates.DateTime(date2) - Dates.DateTime(date1))))

It appears to be huge, but working.

I don’t know if you want to keep the unit and thus round it to nearest second or something like:

julia> (Dates.DateTime(date2) - Dates.DateTime(date1))
6136 milliseconds

julia> (Dates.DateTime(date2) - Dates.DateTime(date1)) / Millisecond(1) * (1 / 1000)
6.136

Assuming you’re going for human-readable, I would do this.

julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.DateTime(date2) - Dates.DateTime(date1)))
6 minutes, 23 seconds
2 Likes

Or just / Millisecond(1000)

1 Like

Thanks for the reply!

I just cannot notice how I can translate the dates (Y-m-d H:i:s) into a timestamp. Any method, or should I develop a function intending to do it ?

Regards,

See the conversion functions to get various timestamps:

julia> using Dates

julia> datetime2unix(DateTime("2018-06-13T04:40:49"))
1.528864849e9
1 Like

Hi,

Thanks for you reply, it appeared the Dates package wasn’t installed on my system. I can now convert my well formed hour to a good old timestamp.

Thanks again!