command to Substract two timestamps in unix

▼魔方 西西 提交于 2021-02-16 20:15:07

问题


I am writing a script and which requires to calculate the difference between the two timestamps . I have done some search but didn't get a clue so far.

For Example say:

time1 = 20160314 10:16:27
time2 = 20160313 15:17:28

From the above I need to get result like below: difference is: "1 day 5 hours 1 minute 1 second"

Please help me in resolving this.


回答1:


datediff() {
    t1=$(date -d "$1" +%s)
    t2=$(date -d "$2" +%s)
    diff=$(( $t1 - $t2 ))

    echo "Duration: $(( $diff / 86400 )) days $(($diff / 3600 )) hours $((( $diff % 3600) / 60)) minutes $(( $diff % 60 )) seconds"
}

date -d "$1" +%s converts given date to time stamp(counted from 1970).

More details on date conversion

http://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html#Date-input-formats

example:

$ date -d 2013-07-05 +%m/%d/%Y
07/05/2013
$ date -d 07/05/2013 +%F
2013-07-05



回答2:


The command you likely want to use is date, but its usage depends on your operating system. You've specified unix in the tags on your question, which isn't really specific enough for a single answer.

In general though, you'll calculate differences between dates by counting the seconds between them. So your method should be to figure out the unix epoch second for each of your dates, subtract to find the difference, and then print the results in whatever format suits you.

In Linux, GNU date (from "coreutils") has a -d option that can understand a number of date references.

$ time1="20160314 10:16:27"
$ date -d "$time1" '+%s'
1457964987

And you can calculate the difference in seconds between two dates like this:

echo "$(( $(date -d "$time1" '+%s') - $(date -d "$time2" '+%s') ))"

Converting that to your output format is a simple matter of division and remainders:

s=$(( $(date -d "$time1" '+%s') - $(date -d "$time2" '+%s') ))

printf "%d day(s) %d hours %d minute %d second\n" \
   $(( s / 86400 )) \
   $(( s % 86400 / 3600 )) \
   $(( s % 3600 / 60 )) \
   $(( s % 60 ))

In FreeBSD, on the other hand, the -d option does something completely different, and you'd use -f and -v to parse and adjust a date. For example:

$ time1="20160314 10:16:27"
$ date -j -f '%Y%m%d %T' "$time1" '+%s'
1457964987

Figuring out the difference looks similar to the Linux method then:

s=$(( $(date -j -f '%Y%m%d %T' "$time1" '+%s') - $(date -j -f '%Y%m%d %T' "$time2" '+%s') ))

You can then use the same printf command I've shown above to format your output.

I don't have details on how the date command works in Solaris or other operating systems, but you can man date from a shell to see if either of these strategies appears to be compatible with whatever operating system you're running.



来源:https://stackoverflow.com/questions/35991742/command-to-substract-two-timestamps-in-unix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!