4

I have a date in milliseconds since Unix epoch format, how do I substract 5 minutes from it?

Alexiel
  • 149

5 Answers5

10

Supposing your timestamp is in a variable timestamp, and in milliseconds since the epoch:

fiveminutesbefore=$((timestamp - 5 * 60 * 1000))

This uses arithmetic expansion to subtract 5 lots of 60 (seconds in a minute) lots of 1000 (milliseconds in a second) from your value timestamp, giving a time five minutes earlier as you would expect.

Michael Homer
  • 76,565
  • My timestamp is actually passed as an argument into my bash script, and it won't do ss=$(($1-5601000))...How can I convert it before substracting? – Alexiel Sep 22 '14 at 05:19
  • Are you sure this is Bash? ss=$(($1-5*60*1000)) is valid and working Bash. You can save it in a named variable first if you want: timestamp=$1, but it shouldn't make any difference. Do you get an error message? If so, what is it? – Michael Homer Sep 22 '14 at 05:26
  • There was an error, the argument had an incorrect format! Thanks for your anser) – Alexiel Sep 22 '14 at 08:58
4

5 minutes of 60 seconds of 1000 milliseconds each gives 300000.

You can subtract this from a variable that containts current date in milliseconds using $(( )):

dd=$(($(date +'%s * 1000 + %-N / 1000000')))
ddmin5=$(($dd - 300000))
echo $ddmin5

The milliseconds calculation comes from this answer

Anthon
  • 79,293
  • 2
    The nice thing about the "seconds since epoch" format is that for a computation like this, there is no need to consider time zones or corner cases for daylight savings or leap seconds. – Nate Eldredge Sep 22 '14 at 05:12
1

There are too many ways:

fiveminutesbefore=$[$timestamp - 5 * 60 * 1000]

or

fiveminutesbefore=`echo "$timestamp - 5 * 60 * 1000" | bc -l`

or

fiveminutesbefore=`echo "$timestamp" | python -c 'import sys; t=sys.stdin.read(); print int(t) - 5 * 60 * 1000'`

etc...

unknown
  • 11
  • Hello and welcome to ul.sx! Please be specific and ensure your answers are always complete, including stating you answer's idea before providing code snippets. – Bananguin Sep 22 '14 at 10:36
0

Using GNU awk for the strftime() function and the FIELDWIDTHS variable.

$ awk -v FIELDWIDTHS='10 3' '{ print strftime("%s" $2, $1-5*60) }' <<<'1623660409789'
1623660109789
αғsнιη
  • 41,407
-3

print solaris sun os minus 10min

dt="$(date +%H:"$(( `date +%M`-10))":%S)"