Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert milliseconds timestamp to date from unix command line

Tags:

date

unix

awk

I know about

date -d @<timestamp in seconds> 

and

awk '{print strftime("%c", <timestamp in seconds>)}' 

but what if I have milliseconds. Is there trivial way to do this without dropping the final three characters of the millisecond-timestamp (not that dropping characters is difficult, but I would think there'd be a one-step way for such a straightforward task)?

like image 786
jonderry Avatar asked Sep 11 '12 03:09

jonderry


People also ask

How do you convert milliseconds to date format?

Use the Date() constructor to convert milliseconds to a date, e.g. const date = new Date(timestamp) . The Date() constructor takes an integer value that represents the number of milliseconds since January 1, 1970, 00:00:00 UTC and returns a Date object.

How do I convert a timestamp to a date?

You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.

How do I get milliseconds in Unix?

date +"%T. %6N" returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds. date +"%T. %3N" returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.


2 Answers

What I have in my bash profile on Mac:

day() {   date -r $(($1 / 1000)) } 

day 1486743904359 returns Fri Feb 10 08:25:04 PST 2017

like image 28
Zaheer Avatar answered Oct 22 '22 10:10

Zaheer


Instead of dropping characters, you could divide by 1000:

awk '{print strftime("%c", ( <timestamp in milliseconds> + 500 ) / 1000 )}' 

Or:

date -d @$(  echo "(MilliSecondTimeStamp + 500) / 1000" | bc) 

Or (MacOS):

gdate -d @$(  echo "(MilliSecondTimeStamp + 500) / 1000" | bc) 

Edit: Adjusted for the quotients instead of division. Edit2: Thx zeekvfu, fixed.

like image 182
joepd Avatar answered Oct 22 '22 10:10

joepd