Reputation: 427
I am splitting a 24-hour timeframe API call into an hourly one. I need to create time intervals like 00:00-01:00, 01:00-02:00, ... and assign them to variables start_time and stop_time to be used in the call.
Got this so far:
date=$'20210825'
for i in {0..23}
start_time=$(date -d $date "+ "$i"hour" +%s)"000"
stop_time=$(date -d $date "+ "$i+1"hour" +%s)"000"
echo $start_time
echo $stop_time
API call happens here inside for loop
But it complains about syntax error. Any ideas on how to correctly increment the variables?
Upvotes: 0
Views: 487
Reputation: 189417
As long as the time intervals are within the same day, there is no need to call date
multiple times. Just call it once to get the baseline, then add to that.
baseline=$(date -d 2021-08-25 +%s)
for((i=0; i<24*3600; i += 3600)); do
start_time=$((baseline+i))"000"
stop_time=$((baseline+i+3600))"000"
printf '%s\n' "$start_time" "$stop_time"
done
I'm wondering if the stop time shouldn't be the start time plus 3599.999, though.
This "C-style" for
loop syntax is a Bash extension, and not portable to POSIX sh
etc.
Upvotes: 0
Reputation: 10064
This is what I did in the past for similar scenario:
year='2021'
month='08'
date='25'
for i in {0..23}
do
end=$(($i + 1))
start_time=$(date -v ${year}y -v ${month}m -v${date}d -v${i}H -v0M -v0S +%s)"000"
stop_time=$(date -v ${year}y -v ${month}m -v${date}d -v${end}H -v0M -v0S +%s)"000"
echo $start_time
echo $stop_time
done
Upvotes: 1
Reputation: 43983
You can use the following date
format:
start_time=$(date -d "${date} + ${i} hour" +%s)"000"
The +1
can be done using the $((...))
syntax:
"${date} + $((i + 1)) hour"
So the script becomes:
date=$'20210825'
for i in {0..23}; do
start_time=$(date -d "${date} + ${i} hour" +%s)"000"
stop_time=$(date -d "${date} + $((i + 1)) hour" +%s)"000"
echo $start_time
echo $stop_time
echo -e
done
Output:
1629849600000
1629853200000
1629853200000
1629856800000
1629856800000
1629860400000
1629860400000
1629864000000
1629864000000
1629867600000
1629867600000
1629871200000
1629871200000
1629874800000
1629874800000
1629878400000
1629878400000
1629882000000
1629882000000
1629885600000
1629885600000
1629889200000
1629889200000
1629892800000
1629892800000
1629896400000
1629896400000
1629900000000
1629900000000
1629903600000
1629903600000
1629907200000
1629907200000
1629910800000
1629910800000
1629914400000
1629914400000
1629918000000
1629918000000
1629921600000
1629921600000
1629925200000
1629925200000
1629928800000
1629928800000
1629932400000
1629932400000
1629936000000
Upvotes: 2