3

I need to get the date and time of the command date minus 5 mins.

date:
29 Aug 2018 21:56:01

result:
29 Aug 2018 21:51:02

I tried to search on the Internet/forums but most of it involved using the -d option and what I have doesn't support the -d option.

This one works on Bash but I need something that works on ksh.

$ printf "%(%d %h %Y %H:%M:%S)T\n" $(( $(printf "%(%s)T") - 5 * 60 ))
4
  • What ksh version do you have? ksh --version. And can you also use perl or python?
    – chaos
    Sep 3, 2018 at 5:34
  • ksh --version is not working for me. I can use perl. Sep 3, 2018 at 5:43
  • chaos is indulging in a little GNU Think. (-: The PD Korn shell does not support --version. Neither does the MirBSD Korn shell. The bigger clue as to whether one is using 93 Korn is the 93 in the name of the command, ksh93 as it usually is, not ksh as chaos said (which is PD Korn on several operating systems, not 93 Korn).
    – JdeBP
    Sep 3, 2018 at 10:44
  • Why are you demonstrating a 4:59 difference when the title says 5 minutes?
    – Jeff Schaller
    Sep 3, 2018 at 11:47

2 Answers 2

6

bash actually copied the %(...)T format from ksh93 but only a small subset.

That's much more powerful in ksh93.

$ date; printf '%(%c)T\n' 'exactly five minutes ago'
Mon  3 Sep 08:08:32 BST 2018
Mon Sep  3 08:03:32 2018

bash only supports Unix epoch times (or -1 for now, though with recent versions you can also get now with a missing argument) while ksh93 supports complex relative (including English like above, crontab, at, ISO 8601:2004 durations) or absolute time specifications (see the test data in the source for some examples).

In ksh93, if you want to pass an epoch time, you use a # prefix:

$ printf '%(%c)T\n' '#0'
Thu Jan  1 00:00:00 1970

(though here, it happens to give the incorrect time for me in a British timezone where epoch time 0 was at 1am)

2

You could use perl:

echo $(( $(printf "%(%s)T") - 5 * 60 )) | perl -lne 'print scalar localtime $_'

Or in pure perl:

perl -le 'print scalar localtime(time()-5*60)'

To format use strftime():

perl -MPOSIX=strftime -le 'print strftime("%d %h %Y %H:%M:%S", localtime(time()-5*60))'
2
  • The second one works. Thanks! Im not familiar with perl. How can I convert it to match the format above? Sep 3, 2018 at 6:05
  • @WaldenSchmidt see my edit
    – chaos
    Sep 3, 2018 at 6:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .