0

I have a date in YYYY.MM.DD HH:SS format (e.g. 2014.02.14 13:30). I'd like to convert it in seconds since epoch using the date command.

The command

date -d"2014.02.14 13:30" +%s

won't work, because of the dots separation.

Any Ideas?

2
  • What are the constraints? If you can do it in a bash script, so convert it and strip dots, and then convert to epoch. Commented Nov 7, 2014 at 19:33
  • Just a note: on freebsd there is -f Commented Nov 7, 2014 at 19:36

5 Answers 5

2

Why don't you make the date format acceptable? Just replace dots with dashes:

$ date --date="`echo '2014.02.14 13:30' | sed 's/\./-/g'`" +%s 1392370200 

Here I first change the format:

$ echo '2014.02.14 13:30' | sed 's/\./-/g' 2014-02-14 13:30 

and then use the result as a parameter for date.

Note that the result depends on your timezone.

Sign up to request clarification or add additional context in comments.

2 Comments

I should've mentioned that it acted piped in an awk command: awk 'BEGIN{getline}{command=("date --date=\""$1" "$2"\""); while (....
Then make the same replacement in awk using its gsub function.
2

You can use:

s='2014.02.14 13:30' date -d "${s//./}" Fri Feb 14 13:30:00 EST 2014 

To get EPOCH value:

date -d "${s//./}" '+%s' 1392402600 

2 Comments

why no of seconds differ?? in each ans??
ohh its due to EST AND IST got it :)
1

using awk :

s=`echo "2014.02.14 13:30" | awk '{gsub(/\./,"-",$0);print $0}'` echo -d "$s" date -d "$s" +%s 

output:

Fri Feb 14 13:30:00 IST 2014 1392364800 

Comments

1

Perl: does not require you to munge the string

d="2014.02.14 13:30" epoch_time=$(perl -MTime::Piece -E 'say Time::Piece->strptime(shift, "%Y.%m.%d %H:%M")->epoch' "$d") echo $epoch_time 
1392384600 

Timezone: Canada/Eastern

1 Comment

thanks, perl seems powerful, but one language at a time.
0

I Finally solved it using

awk 'BEGIN{FS=","}{ gsub(/./," ",$1);gsub(/:/," ",$2); var=sprintf("%s %s 00",$1,$2); print mktime(var), $3,$4,$5,$6,$7 }' myfile | less

so myfile:

2014.09.24,15:15,1.27921,1.27933,1.279,1.27924,234

became

1411582500 1.27921 1.27933 1.279 1.27924 234

:)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.