11

Using the date program, how can I calculate the number of seconds since midnight?

  • 1
    date "+(%H*60+%M)*60+%S" | bc – groxxda Jul 25 '14 at 13:42
  • 1
    echo $(($(date '+(%H*60+%M)*60+%S'))) – groxxda Jul 25 '14 at 13:59
14

To avoid race conditions, still assuming GNU date:

eval "$(date +'today=%F now=%s')"
midnight=$(date -d "$today 0" +%s)
echo "$((now - midnight))"

With zsh, you can do it internally:

zmodload zsh/datetime
now=$EPOCHSECONDS
strftime -s today %F $now
strftime -rs midnight %F $today
echo $((now - midnight))

Portably, in timezones where there's no daylight saving switch, you could do:

IFS=:
set -- $(date +%T)
echo "$((${1#0} * 3600 + ${2#0} * 60 + ${3#0}))"

The ${X#0} is to strip leading 0s which in some shells like bash, dash and posh cause problems with 09 (where the shell complains about it being an invalid octal number).

  • Very clever and good use of eval – Ulrich Dangel Jul 25 '14 at 13:14
  • I'd rather use something along these lines: IFS=: read -r today now <<< $(date +%F:%s); midnight=$(date -d "$today 0" +%s); echo $(( now - midnight )) – x-yuri May 3 '18 at 20:41
7

There is no need for any arithmetic expression, just use pure date:

date -d "1970-01-01 UTC $(date +%T)" +%s
  • Great answer, should be the top one. – Leopoldo Sanczyk Mar 28 at 19:02
  • 1
    On Mac brew install coreutils and replace date with gdate – Connor McCormick Aug 12 at 20:48
2

Based on bash, get current time in milliseconds since midnight, on a GNU system, it can be done like this:

$ now=$(date '+%s')
$ midnight=$(date -d 'today 00:00:00' '+%s')
$ echo $(( now - midnight ))
53983
  • 2
    You want to make sure you don't do that at 23:59:59 – Stéphane Chazelas Jul 25 '14 at 13:02
  • And to convert back: date -d @$seconds – choroba Jul 25 '14 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.