2017-11-10 12 views

답변

2

당신은 당신의 자신의 기능을 할 수 있습니다 :이 가장 효율적인 방법입니다, 그러나 이것은 예를 들어 작동하는 경우

확실하지. 알아야 할 주요 기능은 divrem입니다. 이는 편리한 함수 호출에서 제수와 나머지를 제공합니다.

dt=3600.125 

function hmss(dt) 
    (h,r) = divrem(dt,60*60) 
    (m,r) = divrem(r, 60) 
    #(s,r) = divrem(r, 60) 
    string(Int(h),":",Int(m),":",r) 
end 

hmss(dt) 

hmss(3452.98) 
+0

줄리아의 DateTime 지원이 그토록 훌륭 할 때 왜 그렇게했을까요? –

+0

어떻게 가르치는 것이 무엇보다 중요하기 때문입니다. ppl 누가 내 방법을 네이티브 datetime으로 이동할 수 있지만 다른 주위가 어렵습니다 – xiaodai

+1

또한이 경우 DateTime을 사용하기가 번거롭기 때문에. 일부 기능 호출, 형식 지정 및 몇 가지 트릭이 필요합니다. 예 : 예를 들어 Liso의 대답은 아래에 나와 있습니다. xiaodai의 솔루션은 짧고 간단합니다. –

2

dates section in the manual을 살펴보십시오.

julia> Dates.format(DateTime("2017-10-01T01:02:03"), "H:M:S.s") 
"1:2:3.0" 
+0

예! 필자는 Julia의 DateTime 조작을 위해 강력한 inbuilt 기능을 사용하는 것이 좋습니다. –

+1

@ MichaelK.Borregaard는 내 대답을보고 "inbuilt facilities"를 더 잘 활용할 수 있습니까? 내 관점에서 볼 때 Julia에서는 여전히 조금 복잡합니다. 예를 들어'Dates.format (Dates.Nanosecond (1e8), dateformat "S.s")'가 작동 할 수 있다고 기대합니다. – Liso

+0

이 aswer는 3600 * 24 초 미만의 기간 동안 문제를 해결합니다. 그러나 가짜 날짜가 필요합니다. –

1

날짜 형식으로 변환하면 this method을 사용할 수 있습니다.

julia> t1 = now() 
2017-11-10T10:00:51.974 
# Wait 
julia> t2 = now() 
2017-11-10T10:10:07.895 
julia> x = Dates.canonicalize(Dates.CompoundPeriod(t2-t1)) 
9 minutes, 15 seconds, 921 milliseconds 

julia> x.periods 
3-element Array{Base.Dates.Period,1}: 
9 minutes  
15 seconds  
921 milliseconds 

julia> x.periods[2] 
15 seconds 

julia> x.periods[2].value 
18 
0
""" working properly only if 0<= sec <=86400 otherwise truncating """ 
function fmtsec(sec, fmt::Dates.DateFormat) 
    # nanos = Dates.Nanosecond(sec * 1e9) # we could get InexactError here! 
    nanos = Dates.Nanosecond(trunc(Int, sec * 1e9)) 
    mytime = Dates.Time(nanos) 
    Dates.format(mytime, fmt) 
end 

fmt = dateformat"H:M:S.s" # Creating a DateFormat object is expensive. (see doc) 

fmtsec(3600.125, fmt) # "1:0:0.125" 

편집 : 절단 나노초없이 우리는 오류를 얻을 수 ->

julia> tic();sleep(1);old_fmtsec(toc(), dateformat"S.s") 
elapsed time: 1.002896514 seconds 
ERROR: InexactError() 
Stacktrace: 
[1] convert(::Type{Int64}, ::Float64) at ./float.jl:679 
[2] fmtsec(::Float64, ::DateFormat{Symbol("S.s"),Tuple{Base.Dates.DatePart{'S'},Base.Dates.Delim{Char,1},Base.Dates.DatePart{'s'}}}) at ./REPL[47]:2 

julia> tic();sleep(1);old_fmtsec(toc(), dateformat"S.s") 
elapsed time: 1.002857122 seconds 
"1.002" 

tic & toc

이되지 않습니다. toc은 내부적으로 time_ns를 사용하기 때문에 반올림 오류가 발생할 수 있지만 nanoseconds는 1e9로 나눈 초로 변환됩니다.