Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

more efficient HH:MM:SS conversion possible?

I'm wondering please if there is a more efficient way to convert HH:MM:SS to decimal hours for the ordinate (y) axis of gnuplot, with dates on the (x) abscissa. Some of these plots have many thousands of data points and take much time to convert the hours to decimal.

A data set (/tmp/fn) looks like:

...
2022 Aug 21 05:35:16
2022 Aug 22 14:53:33
2022 Aug 31 14:11:55
2022 Sep 03 18:24:29
2022 Sep 03 18:24:56
2022 Sep 04 06:55:29
2022 Sep 04 06:55:44
2022 Sep 05 16:01:57
2022 Sep 05 16:02:16
2022 Sep 06 04:20:26
...

My current method is bash shell with:

...
# change HH:MM:SS to "d"ecimal hours
for t in $(awk '{print $NF}' /tmp/fn)
do 
  read H M S < <(echo $t | sed 's|:| |g')
  d=$(echo "scale=4; $H + $M/60 + $S/3600" | bc 2>/dev/null)
  sed -i "s|$t|$d|g" /tmp/fn
done
...

[edit]Sorry, I thought the simple sed construct indicated the desired output:

...
2022 Aug 21 5.5877
2022 Aug 22 14.8924
...

[/edit]

It would be very helpful if this could be made more efficient and less time-consuming, as a datafile with 9k entries consumes about 42 secs for the conversion, and much larger datasets are possible.

python or perl expressions are also welcomed. Thank you for your considerations.

like image 443
dwarnok Avatar asked Jul 07 '26 16:07

dwarnok


2 Answers

Using a perl one-liner:

$ perl -pe 's{(\d\d):(\d\d):(\d\d)$}{sprintf("%.4f", $1 + ($2/60.0) + ($3/3600.0))}e' fn.txt
2022 Aug 21 5.5878
2022 Aug 22 14.8925
2022 Aug 31 14.1986
2022 Sep 03 18.4081
2022 Sep 03 18.4156
2022 Sep 04 6.9247
2022 Sep 04 6.9289
2022 Sep 05 16.0325
2022 Sep 05 16.0378
2022 Sep 06 4.3406

If you want to modify the file directly and that's the desired format, add the -i option: perl -pi -e ...

like image 105
Shawn Avatar answered Jul 10 '26 07:07

Shawn


I'm with dawg.
I really don't understand why you would explicitly use awk in your loop and not just do the entire task there.

$ awk -F'[: ]' '{ printf "%s %s %s %.4f\n", $1, $2, $3, $4+$5/60+$6/3600 }' file
2022 Aug 21 5.5878
2022 Aug 22 14.8925
2022 Aug 31 14.1986
2022 Sep 03 18.4081
2022 Sep 03 18.4156
2022 Sep 04 6.9247
2022 Sep 04 6.9289
2022 Sep 05 16.0325
2022 Sep 05 16.0378
2022 Sep 06 4.3406
like image 35
Paul Hodges Avatar answered Jul 10 '26 07:07

Paul Hodges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!