-1

I have two timestamps in formats :

Timestamp 1 (Variable - RunStartDate): Thu May 3 14:12:54 CDT 2018
Timestamp 2 (Variable - RunEndDate): Thu May 3 18:11:46 CDT 2018

I want the difference of number of hours between these two timestamps in UNIX shell. (I.e. RunEndDate - RunStartDate in hours)

Please help, I am new to UNIX and it is throwing me errors when I just try to subtract the two.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116

1 Answers1

3

You have a few options here, such as calling out to Perl or Python and using a date/time library to do the math for you. Another option is to use the date program to convert the dates to seconds, subtract the values, and then convert back to hours. Unfortunately, you can't do floating-point math in Bash, so we'll have to call out to a helper program to do that, too.

START=$(date -d "$RunStartDate" +"%s")
END=$(date -d "$RunEndDate" +"%s")
HOURS=$(bc -l <<< "($END - $START) / 3600")

Note that this will only work on GNU systems (e.g. Linux).

mwp
  • 8,217
  • 20
  • 26
  • Thanks..can the same be used in shell in UNIX? How to modify to work in shell without calling Perl or Python. I am calling shell from Datastage that's why. – Manoj Srivastava May 03 '18 at 20:04
  • @Manoj, what does `date --version` show you? Or perhaps `what "$(which date)"` – glenn jackman May 03 '18 at 20:06
  • when I type "date" in UNIX shell, it is giving me format : Thu May 3 14:12:54 CDT 2018 – Manoj Srivastava May 03 '18 at 20:08
  • @ManojSrivastava, The `date` command can't portably be relied on to provide `%s`. If you're running IBM Datastage, then you're probably in z/OS and neither your `date` nor your `strftime` command has a `%s`. You can calculate your epoch second using math, but you also can't rely on `date` to be able to convert an epoch second back to a formatted date. Can you confirm that the unix you're in is z/OS? Also, what shell are you using? Bash? Zah? POSIX? (please [not tcsh](http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/).) – ghoti May 07 '18 at 04:30
  • @ghoti The question is RE: UNIX, so—assuming the submitter is not completely clueless—it's probably not z/OS. (z/OS is not UNIX. It does have UNIX System Services, but that's like calling Windows Linux because of WSL. Does USS even provide a full UNIX shell?) DataStage runs quite comfortably on Solaris, Linux, AIX, HP-UX, etc., so it's safer to assume it's one of those. But perhaps we should ask for clarification. – mwp May 07 '18 at 05:15
  • So of the four operating systems you've listed, your answer will only work in one of them. I'd suggest that it's not really safe to assume anything. The question is indeed incomplete, and includes no code that the OP needs help with. It's the sort of question that should be closed rather than answered. Which is not a criticism of the OP, just recognition that it takes some research and effort to create quality questions here. – ghoti May 08 '18 at 05:23