Sign up ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

I would like to write a bash script that prints out the date in the following format:

(year)(month)(day)_(24 hour)

so the command to do this for the current date is:

date +'20%y%m%d_%H'

What i would like to do is print every date like this (using a for loop or something) from a specified date to another. For example:

20120205_16 -> 20120305_18 would be:


Is it possible to do this easily with date or another method?

share|improve this question
This list of resources might help:… –  user76204 Aug 16 '12 at 0:30

1 Answer 1

up vote 3 down vote accepted

Print every date between a Time duration

  1. I would grab your date1 and date2 and convert them to timestamps
  2. Then I would investigate: whats 1 hour converted to timestamp.
  3. And write a for-loop from timestamp(date1) to timestamp(date2)

within the loop I would add step by step timestamp(1 hour), convert the new timestamp back in the prefered date/time format and print it out until the loop ends. #

# by user85321 @ ask ubuntu
# call: ./ 20120205_16 20120205_16 20120305_18

# STEP 1:
# set userdefined Dateformat to normal
d1=$(echo "$1" | sed 's/_/ /g')
d2=$(echo "$2" | sed 's/_/ /g')

# set normalized dates to timestamps
t1=$(date --utc --date "$d1" +%s)
t2=$(date --utc --date "$d2" +%s)

# STEP 2:
# time increment, 1h = 3600 s

# STEP 3:
if [ $t2 -gt $t1 ]
    for i in $(seq $t1 $h $(($t2-$h)))
        # take this and do what you want to do ;o)      
        echo $(date --date="@$i" "+%Y%m%d_%H")

My bash prints out exactly that list , what you described . So, it is done. I think some cracks would do it shorter/ better, but it works ...

good luck

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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