簡體   English   中英

我如何使用 shell 腳本減去 2 個時間戳

[英]How I substract 2 timestamps using shell scripts

我需要使用 shell 腳本減去以下 2 次

var1=2019-11-14-03.00.02.000000

var2=2019-11-14-03.00.50.000000

output 應該是00-00-00-00.00.48.00000

首先將var1var2轉換為以秒為單位的日期(自紀元以來):

sec1=$(date --date $var1 +%s)
...

使用 bash 數學運算符計算差值

delta=$((sec1 - sec2))

最后將其轉換回可讀格式

date --date @1502938801"$delta"

正如我在評論中提到的, var1var2不是使用-d選項傳遞給 GNU date的有效日期格式。 在將時間從紀元轉換為秒之前,您必須

  • 刪除每個變量的日期和時間部分之間的'-'
  • 單獨隔離時間,
  • 刪除毫秒
  • 替換所有'.' 在與':'的時間
  • '.'恢復與時間分開的毫秒數。
  • 將重新格式化的字符串傳遞給每個date -d"$dt $tm" +%s ,重新格式化的日期和時間以空格分隔。

Bash 提供參數替換以非常輕松地處理每個參數。

在計算兩個紀元以來的時間並取差后,您必須手動計算年、月、日、小時、分鍾、秒和毫秒的差異,以便 output 差異,並且您必須使用printf格式化 output integer轉換說明符使用適當的字段寬度前導零修飾符。

總而言之,(並使用365-day/year30-day/mo近似值)您可以這樣做:

#!/bin/bash

var1=2019-11-14-03.00.02.000000
var2=2019-11-14-03.00.50.000000

dt1=${var1%-*}      ## isolate date portion of variables
dt2=${var2%-*}

tm1=${var1##*-}     ## isolate time portion of variables
tm2=${var2##*-}

ms1=${tm1##*.}      ## isolate milliseconds portion of variables
ms2=${tm2##*.}

tm1=${tm1%.*}       ## remove milliseconds from time
tm2=${tm2%.*}

tm1=${tm1//./:}     ## substitute all . with : in times w/o milliseconds
tm2=${tm2//./:}

tm1=${tm1}.$ms1     ## restore milliseconds
tm2=${tm2}.$ms2

epoch1=$(date -d"$dt1 $tm1" +%s)    ## get time since epoch for both
epoch2=$(date -d"$dt2 $tm2" +%s)

epochdiff=$((epoch2-epoch1))        ## get difference in epoch times

## Approximates w/o month or leap year considerations
y=$((epochdiff/(3600*24*365)))      ## years difference
rem=$((epochdiff-y))                ## remainder
m=$((rem/(3600*24*30)))             ## months difference (based on 30 day mo)
rem=$((rem-m))                      ## remainder
d=$((rem/(3600*24)))                ## days difference
rem=$((rem-m))                      ## remainder
H=$((rem/3600))                     ## hours difference
rem=$((rem-H))                      ## remainder
M=$((rem/60))                       ## minutes difference
S=$((rem-M))                        ## secnds difference
ms=$((ms2-ms1))                     ## millisecond difference

## format output
printf "%04d-%02d-%02d-%02d:%02d:%02d.%04d\n" $y $m $d $H $M $S $ms

注意:您可以進一步微調月份和年份/閏年的計算——這留給您)

示例使用/輸出

$ bash ~/scr/dtm/fulltimediff.sh
0000-00-00-00:00:48.0000

如果您還有其他問題,請仔細查看並告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM