简体   繁体   中英

How to find time difference in seconds between 2 dates in bash?

I currently have the variables below and want to know how much time elapsed in seconds. So CURRENT_TIME - TEST_START

TEST_START=$(date '+%d/%m/%Y %H:%M:%S')
sleep 4
CURRENT_TIME=$(date '+%d/%m/%Y %H:%M:%S')

I tried below, but keep getting illegal action

START_IN_SECONDS=$(date --date "$(TEST_START)" +%s)

This is in Mac.

#!/bin/bash

# Time Arithmetic

TIME1=05:36:11
TIME2=06:46:00

# Convert the times to seconds from the Epoch
SEC1=`date +%s -d ${TIME1}`
SEC2=`date +%s -d ${TIME2}`

# Use expr to do the math, let's say TIME1 was the start and TIME2 was the finish
DIFFSEC=`expr ${SEC2} - ${SEC1}`

echo Start ${TIME1}
echo Finish ${TIME2}

echo Took ${DIFFSEC} seconds.

# And use date to convert the seconds back to something more meaningful
echo Took `date +%H:%M:%S -ud @${DIFFSEC}`

Output:

Start 05:36:11
Finish 06:46:00
Took 4189 seconds.
Took 01:09:49

First, the syntax for expanding variables is $variable or ${variable} , not $(variable) .

Second, date doesn't know how to parse dates that are in %d/%m/%Y format. When the date uses slashes, it expects it to be %m/%d/%Y . So change your first two lines to use the correct format.

TEST_START=$(date '+%m/%d/%Y %H:%M:%S')
sleep 4
CURRENT_TIME=$(date '+%m/%d/%Y %H:%M:%S')
START_IN_SECONDS=$(date --date "$TEST_START" +%s)
CURRENT_IN_SECONDS=$(date --date "$CURRENT_TIME" +%s)
diff=$((CURRENT_IN_SECONDS - START_IN_SECONDS))
echo $diff

Of course, you could just set the xxx_IN_SECONDS variables directly with +%s instead of parsing formatted dates:

START_IN_SECONDS=$(date +%s)
sleep 4
CURRENT_IN_SECONDS=$(date +%s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM