how to convert a date HH: MM: SS in second with bash?
Asked Answered
A

5

12

How to convert a date HH: MM: SS in second with bash?

Knowing that this is a date that I recovered in a file so I can't take it in another format.

I have two variables $DateStart and $DateEnd and i would like the difference between both.

Aeschines answered 7/5, 2013 at 8:31 Comment(0)
D
19
date +%s

returns the current datetime in seconds since 1970-01-01 00:00:00 UTC

if you want to get a given datetime in seconds since 1970-01-01 00:00:00 UTC, for example:

kent$  date -d"2008-08-08 20:20:20" +%s
1218219620

to get diff in seconds, you just get the two dates in seconds, and do a s1-s2

Diphthongize answered 7/5, 2013 at 8:37 Comment(2)
Note that if timestamps don't contain dates, date should still be supplied with them. Otherwise, if only times are passed, date will assume today and times calculated on either side of midnight will have additional 24 hour difference between them.Yetac
Thanks it's works, i do start=$(date -d"$DateStart" +%s) and end=$(date -d"$DateEnd" +%s) and after time=$(end-start).Aeschines
C
10

On a Mac (and probably other BSDs) you can convert a date into another date with a combination of the -j and -f option:

$ date -j -f '%Y-%m-%d %H:%M:%S' "2016-02-22 20:22:14" '+%s'
1456168934

Where -j suppresses changing the system clock, -f <fmt> gives the format to use for parsing the given date, "2016-02-22 20:22:14" is the input date and +<fmt> is the output format.

Candelariacandelario answered 22/2, 2016 at 19:26 Comment(0)
Y
5

Assuming the time in HH:MM:SS format is in variable time_hhmmss and time in seconds needs to be stored in time_s:

IFS=: read -r h m s <<<"$time_hhmmss"
time_s=$(((h * 60 + m) * 60 + s))
Yetac answered 7/5, 2013 at 8:45 Comment(0)
C
2

Try to use my solution with sed+awk:

echo $DateStart | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
echo $DateEnd | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'

it splits the string with sed, then inverts the numbers backwards ("DD hh mm ss" -> "ss mm hh DD") and calculates them with awk. It works even you add days: [[DD-]hh:]mm:ss, eg:

       34:56
    12:34:56
123-12:34:56
Cutcheon answered 7/8, 2014 at 21:14 Comment(1)
This is good but appears to only work down to the minute. Seconds get rounded.Incognizant
M
0

When using the above examples remember to add -u (to use GMT) otherwise 1970-01-01 00:00:00 is not zero :-)

$ date -d"1970-01-01 00:00:00" +%s
-3600

$ date -u -d"1970-01-01 00:00:00" +%s
0
Mcgowan answered 3/10, 2023 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.