Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: conversion between different time periods

Tags:

julia

Full disclosure: I've only been using Julia for about a day, so it may be too soon to ask questions.

I'm not really understanding the utility of the Dates module's Period types. Let's say I had two times and I wanted to find the number of minutes between them. It seems like the natural thing to do would be to subtract the times and then convert the result to minutes. I can deal with not having a Minute constructor (which seems most natural to my Python-addled brain), but it seems like convert should be able to do something.

The "solution" of converting from Millisecond to Int to Minute seems a little gross. What's the better/right/idiomatic way of doing this? (I did RTFM, but maybe the answer is there and I missed it.)

y, m, d = (2015, 03, 16)
hr1, min1, sec1 = (8, 14, 00)
hr2, min2, sec2 = (9, 23, 00)
t1 = DateTime(y, m, d, hr1, min1, sec1)
t2 = DateTime(y, m, d, hr2, min2, sec2)
# println(t2 - t1)  # 4140000 milliseconds
# Minute(t2 - t1)  # ERROR: ArgumentError("Can't convert Millisecond to Minute")
# minute(t2 - t1)  # ERROR: `minute` has no method matching
                   # minute(::Millisecond)
# convert(Minute, (t2-t1))  # ERROR: `convert` has no method matching
                            # convert(::Type{Minute}, ::Millisecond)

delta_t_ms = convert(Int, t2 - t1)

function ms_to_min(time_ms)
    MS_PER_S = 1000
    S_PER_MIN = 60
    # recall that division is floating point unless you use div function
    return div(time_ms, (MS_PER_S * S_PER_MIN))
end

delta_t_min = ms_to_min(delta_t_ms)
println(Minute(delta_t_min))  # 69 minutes

(My apologies for choosing a snicker-inducing time interval. I happened to convert two friends' birthdays into hours and minutes without really thinking about it.)

like image 684
Ryan M Avatar asked Sep 18 '25 00:09

Ryan M


1 Answers

Good question; seems like we should add it! (Disclosure: I made the Dates module).

For real, we had conversions in there at one point, but then for some reason or another they were taken out (I think it revolved around whether inexact conversions should throw errors or not, which has recently been cleaned up quite a bit in Base for Ints/Floats). I think it definitely makes sense to add them back in. We actually have a handful in there for other operations, so obviously they're useful.

As always, it's also a matter of who has the time to code/test/submit and hopefully that's driven by people with real needs for the functionFeel free to submit a PR if you're feeling ambitious!

like image 183
quinnj Avatar answered Sep 23 '25 11:09

quinnj