Convert an ISO date to seconds since epoch in linux bash

Gianluca Ghettini picture Gianluca Ghettini · Feb 14, 2014 · Viewed 20.5k times · Source

I have a date in the ISO format YYYY-MM-DDTHH:SS (e.g. 2014-02-14T12:30). I'd like to convert it in seconds since epoch using only the date command in linux bash.

All the dates refer to UTC locale.

I know that this question is easily eligible for duplicate... there are billions of questions about converting dates from one format to another but I can't find my particular scenario

thank you...

Answer

kguest picture kguest · Feb 14, 2014

With GNU date (from the GNU coreutils package), specify the date to parse with -d and seconds since epoch with %s

$ date -d"2014-02-14T12:30" +%s
1392381000

Note that this will interpret the date to be parsed as being in your local time zone. If you want date to use a specific time zone, you must specify that, either via the variable TZ (which changes the default time zone for date), or in the date string. For UTC:

$ TZ=UTC date -d"2014-02-14T12:30" +%s
1392381000

or in the string, according to ISO 8601:

$ date -d"2014-02-14T12:30Z" +%s
1392381000

See ISO 8601 on Wikipedia for how to specify other time zones in the date string.