25

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

2 Answers 2

36

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.

8
  • 1
    that's exactly what I tried... but it seems to report a wrong number if compared to the one given at epochconverter.com. Can you explain to me what's going on? Feb 14, 2014 at 11:44
  • I mean, "date" output seems to be several hours late from the value given at www.epochconverter.com Feb 14, 2014 at 11:47
  • I tried the "-u" option but it seems not to work. "-u" means set/print UTC coordinates Feb 14, 2014 at 11:50
  • either as BMW suggests or include the timezone in the input to date, so $ date -d"2014-02-14T12:30 EDT" +%s
    – kguest
    Feb 14, 2014 at 11:51
  • 1
    This answer did not address timezones. I edited to add this - hope that's ok.
    – sleske
    Feb 17, 2021 at 9:30
2

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
2
  • 1
    Your answer seems to refer to a specific UNIX variant (MacOS X presumably). Please clarify what variant you are talking about - otherwise this answer is only confusing. For example, on Linux there is no "install" command, and on Debian there is a "coreutils" package, but it does not contain "gdate" (only "date").
    – sleske
    Feb 17, 2021 at 9:17
  • HI @sleske sorry i have moved away from the project and don't have the environmental information you have asked for Sep 10, 2021 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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