bash, obtiene la hora actual en milisegundos desde la medianoche

Is there a way to get the current milliseconds past midnight in bash? And if there is a way to do it entirely in bash, how good or bad is the precision of that timestamp?

preguntado el 23 de abril de 13 a las 13:04

Revise esta pregunta. -

2 Respuestas

You can get today's midnight with:

date -d 'today 00:00:00'

in UNIX stamp:

date -d 'today 00:00:00' "+%s"

So if you want to get the difference, do:

midnight=$(date -d 'today 00:00:00' "+%s")
now=$(date "+%s")
diff_mills=$(( ($now - $midnight) * 1000 ))

as %s indicates seconds, we have to *1000 to get milliseconds.


Con %N (nanoseconds):

midnight=$(date -d 'today 00:00:00' "+%s.%N")
now=$(date "+%s.%N")
diff_mills=$(echo "( $now - $midnight ) * 1000" | bc)

Respondido 23 Abr '13, 14:04

And to get a better precision, you can use +%N to get the nanoseconds. - enfermedad

Sure. Just added for nanoseconds. As it is 10^-9, we have to /10^6 at the end. - fedorqui

Eh, no. %N is nanoseconds in the current second. So absolute time would be %s.%N (%N is helpfully zero padded). - bobbogo

Uhms, I had to investigate how to do it. $(( )) does not work for float, so I am using bc now. Should be ok now, @bobbogo. Thanks for indicating! - fedorqui

And to convert back to int at the end, something like this can be used: INT=${FLOAT/\.*} - user788171

You can also use mod instead of an explicit date difference. So for example, with 1 second resolution:

millis_since_midnight=$[1000 * ( ( `date "+%s"` - 28800 ) % 86400 )]

Note that 28800 is the PST offset from UTC in seconds. This kludge was useful for me on systems like OSX that have BSD time and thus lack the ability to specify --date 'today 00:00:00'.

Respondido 03 ago 13, 01:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.