Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format time period with jq console tool

Tags:

time

jq

I have time in milliseconds and I want to format it to time period. For example like this(not necessary exactly like this): 1d 23h 15m 13s. How can it be done with jq?

like image 485
wjtk Avatar asked Sep 20 '25 12:09

wjtk


1 Answers

Here is a solution which does the calculations directly.

 def roundto(n):   (./n|floor)*n ;
 def timefmt(ms):
   def calcsecs:                             .s_to_m = (.seconds | roundto(60)) | .secs = .seconds - .s_to_m ;
   def calcmins:     .minutes = .s_to_m/60 | .m_to_h = (.minutes | roundto(60)) | .mins = .minutes - .m_to_h ;
   def calchrs:      .hours   = .m_to_h/60 | .h_to_d = (.hours   | roundto(24)) | .hrs  = .hours   - .h_to_d ;
   def calcdays:     .days    = .h_to_d/24 ;
   def fmtelt(e;u):  if e>0 then " \(e)\(u)" else "" end ;
   def fmt:
       .s = " \(.secs)s"
     | .m = fmtelt(.mins; "m")
     | .h = fmtelt(.hrs; "h")
     | .d = fmtelt(.days; "d")
     | "\(.d)\(.h)\(.m)\(.s)"[1:]
   ;
   {seconds: (ms/1000)|floor} | calcsecs | calcmins | calchrs | calcdays | fmt
;     
timefmt($ms)

If this filter is in filter.jq then

$ jq -Mnr --argjson ms 1505752580000 -f filter.jq

outputs

17427d 16h 36m 20s

for smaller intervals only the relevent fields are shown. e.g.

$ jq -Mnr --argjson ms 1505750 -f filter.jq

outputs

25m 5s
like image 127
jq170727 Avatar answered Sep 23 '25 19:09

jq170727