Skip to content
Advertisement

Rounding of the millisecond part in Linux datetime

So I have the date format like this : 2019-10-19 23:55:42.797 and I want the millisecond part to be round of into the second so the output should look something like this: 2019-10-19 23:55:43

I have tried

date -d "2019-10-19 23:55:42.797" "+%Y-%m-%d %H:%M:%S"

but it’s giving me output like 2019-10-19 23:55:42

How should I do this in Linux bash shell?

Advertisement

Answer

This can be done in a single awk like this:

s='2020-12-31 23:59:59.501'
awk -F. 'gsub(/[-:]/, " ", $1) {
   dt = mktime($1)
   if ($2 >= 500) dt++
   print strftime("%F %X", dt)
}' <<< "$s"
2021-01-01 00:00:00
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement