Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an ISO date to seconds since epoch in linux bash

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...

like image 913
Gianluca Ghettini Avatar asked Feb 14 '14 11:02

Gianluca Ghettini


People also ask

How do I convert dates to seconds in bash?

Thanks it's works, i do start=$(date -d"$DateStart" +%s) and end=$(date -d"$DateEnd" +%s) and after time=$(end-start).

How do you convert date to epoch time in bash?

Use the build-in date command and instruct it to output the number of seconds since 1970-01-01 00:00:00 UTC. You can do this by passing a format string as parameter to the date command. The format string for UNIX epoch time is '%s'. To convert a specific date and time into UNIX epoch time, use the -d parameter.

How do I change epoch time in Linux?

To convert the seconds since the epoch started on January 1, 1970 type date -r 1501959335 at the prompt and push enter. Once again, you can replace 1501959335 with any valid Unix time stamp. Type date “$(date -r 1501959335 +'%y%m%d%H%M. %S')” and push enter to set the date since the epoch started.

How do I convert time to seconds in Linux?

time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). If tloc is non-NULL, the return value is also stored in the memory pointed to by tloc.


2 Answers

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.

like image 105
kguest Avatar answered Sep 20 '22 15:09

kguest


It is easier if you install gdate to deal with date strings that have timezones with nano second precision

install coreutils and you will get gdate along

on mac brew install coreutils

gdate --date="2010-10-02T09:35:58.203Z" +%s%N

This is particularly useful when inserting the time series value into influxdb

in a shell script variable = $(gdate --date="2010-10-02T09:35:58.203Z" +%s%N)

echo $variable
like image 40
Mohammed Rafeeq Avatar answered Sep 20 '22 15:09

Mohammed Rafeeq