Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with Unix timestamps in Matlab?

I have some data files with Unix timestamps (in this case, number of milliseconds since Jan 1, 1970 00:00 UTC). I would like to convert these to human-friendly date/time strings (e.g. 31-Aug-2012 11:36:24) in Matlab. Is there an easy way to do this in Matlab, or am I better off using an external library (e.g. java.text.SimpleDateFormat)?

like image 875
robguinness Avatar asked Aug 31 '12 08:08

robguinness


People also ask

How does Unix timestamp work?

Unix time is a way of representing a timestamp by representing the time as the number of seconds since January 1st, 1970 at 00:00:00 UTC. One of the primary benefits of using Unix time is that it can be represented as an integer making it easier to parse and use across different systems.

Is Unix timestamp always UTC?

Unix timestamps are always based on UTC (otherwise known as GMT). It is illogical to think of a Unix timestamp as being in any particular time zone. Unix timestamps do not account for leap seconds.

Are Unix timestamps in milliseconds?

One millisecond = 1/1000 in UNIX time. One second = 1 in UNIX time. One minute = 60 in UNIX time.


2 Answers

How about

date = datestr(unix_time/86400 + datenum(1970,1,1))

if unix_time is given in seconds, unix_time/86400 will give the number of days since Jan. 1st 1970. Add to that the offset used by Matlab's datenum (datenum(0000,1,1) == 1), and you have the amount of days since Jan. 1st, 0000. This can be easily converted to human-readable form by Matlab's datestr.

If you have milliseconds, just use

date = datestr(unix_time/86400/1000 + datenum(1970,1,1))

Wrapped in functions, these would be

function dn = unixtime_to_datenum( unix_time )
    dn = unix_time/86400 + 719529;         %# == datenum(1970,1,1)
end

function dn = unixtime_in_ms_to_datenum( unix_time_ms )
    dn = unix_time_ms/86400000 + 719529;   %# == datenum(1970,1,1)
end

datestr( unixtime_to_datenum( unix_time ) )
like image 114
Rody Oldenhuis Avatar answered Oct 26 '22 05:10

Rody Oldenhuis


Newer versions of MATLAB (verified in R2015a) have a datetime type that is useful for working with and formatting dates and times. You can convert UNIX timestamps into a MATLAB datetime with

dt = datetime( unix_time, 'ConvertFrom', 'posixtime' );

and then use datestr as before for formatting as a string

datestr( dt )
like image 39
Clark Avatar answered Oct 26 '22 05:10

Clark