0

tried this but failed

now=$(date +%Y%m%d%H%M%S)
past=$(date +%Y%m%d%H%M%S -d "${now} -5minutes")
echo $past

result:

date: invalid date ‘20200120175610 -5minutes’

TT

  • Works for me. What's the output of date --version? – muru Jan 20 at 9:11
  • @muru it is date (GNU coreutils) 8.25 – ohmg Jan 20 at 9:12
  • What is the purpose of 'now'? That's the default without -d anyway. Try: date -d '5 mins ago'. – Paul_Pedant Jan 20 at 11:57
1

It seems GNU date cannot parse timestamps in that format. It takes the leading portion to be a year:

% date +%Y%m%d%H%M%S -d 20200120175610 --debug
date: parsed number part: (Y-M-D) 2020012017-56-10
date: input timezone: system default
date: warning: using midnight as starting time: 00:00:00
date: error: invalid date/time value:
date:     user provided time: '(Y-M-D) 2020012017-56-10 00:00:00'
date:        normalized time: '(Y-M-D) 2020012021-08-10 00:00:00'
date:                                  ---- --
date:      possible reasons:
date:        numeric values overflow;
date:        missing timezone
date: invalid date ‘20200120175610’

If it doesn't error out, then it probably didn't overflow, but it's still not doing what you'd expect:

% date +%Y%m%d%H%M%S -d "20200120181002 -5minutes" --debug
date: parsed hybrid part: -5 minutes
date: input timezone: system default
date: warning: using midnight as starting time: 00:00:00
date: starting date/time: '(Y-M-D) 2020012018-10-02 00:00:00'
date: '(Y-M-D) 2020012018-10-02 00:00:00' = 63745360147926000 epoch-seconds
date: after time adjustment (+0 hours, -5 minutes, +0 seconds, +0 ns),
date:     new time = 63745360147925700 epoch-seconds
date: timezone: system default
date: final: 63745360147925700.000000000 (epoch-seconds)
date: final: (Y-M-D) 2020012018-10-01 14:55:00 (UTC)
date: final: (Y-M-D) 2020012018-10-01 23:55:00 (UTC+09)
20200120181001235500

Use a different timestamp format. I suggest using ISO-8601, and reformatting as needed when outputing:

% now=$(date --iso-8601=seconds)
% past=$(date -d "$now - 5 minutes" --iso-8601=seconds)
% printf "%s\n" "$now" "$past"
2020-01-20T18:29:50+09:00
2020-01-20T18:24:50+09:00
% date -d "$past" +%Y%m%d%H%M%S
20200120182450
|improve this answer|||||
  • you are perfect – ohmg Jan 21 at 4:41
1

This works for me, using date (GNU coreutils) 8.26.

$ date -d "5 minutes ago" +%Y%m%d%H%M%S
20200120101533
|improve this answer|||||
1

It might work like this.

past=$(date +%Y%m%d%H%M%S -d ${now} -d "-5minutes")
|improve this answer|||||
  • didn't use $now – ohmg Jan 21 at 4:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.