How to work with Unix timestamps in Matlab?

寵の児 提交于 2019-11-26 14:03:29

问题


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)?


回答1:


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



回答2:


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 )


来源:https://stackoverflow.com/questions/12211710/how-to-work-with-unix-timestamps-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!