Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash convert string to timestamp

Tags:

bash

sh

I have a string in format 20141225093000 which represents Dec 25, 2014 09:30:00 and I want to convert the original format to a unix timestamp format so i can do time operations on it.How would I do this in bash?

I can easily parse out the values with expr but I was hoping to be able to identify a format like YYYYmmddHHMMSS and then convert it based on that.

like image 802
user3979986 Avatar asked Feb 11 '26 14:02

user3979986


2 Answers

With GNU date, you can convert YYYY-MM-DDTHH:MM:SS to epoch time (seconds since 1-1-1970) easily, like so:

date -d '2014-12-25T09:30:00' +%s

To do this starting without any delimiters:

in=20141225093000
rfc_form="${in:0:4}-${in:4:2}-${in:6:2}T${in:8:2}:${in:10:2}:${in:12:2}"
epoch_time=$(date -d "$rfc_form" +%s)
like image 161
Charles Duffy Avatar answered Feb 15 '26 17:02

Charles Duffy


You need to transform the string before calling date:

#!/bin/bash

s="20141225093000"
s=$(perl -pe 's/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/$1-$2-$3 $4:$5:$6/g' <<< "$s")
date -d "$s" +%s

Yet another way:

perl -MDate::Parse -MPOSIX -le '$s="20141225093000"; $s =~ s/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/$1-$2-$3 $4:$5:$6/g ; print str2time($s);'
1419499800
like image 43
Tiago Lopo Avatar answered Feb 15 '26 18:02

Tiago Lopo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!