且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用R从MATLAB序列号中提取时间?

更新时间:2023-02-26 15:50:10

诀窍是Matlab使用虚构的参考日期"January 01,0000"来计算其日期数字. R中"POSIXct"类的时间起点是"1970-01-01 00:00.00 UTC".您可以在此处中了解不同系统如何处理日期.. >

在转换之前,您需要考虑从一种格式到另一种格式的引用差异. POSIX 手册包含以下内容:一个例子.这是我的输出:

> val<-733038.6
> as.POSIXct((val - 719529)*86400, origin = "1970-01-01", tz = "UTC")
[1] "2006-12-27 14:23:59 UTC"

在Matlab的日期编号中,719529是"1970-01-01 00:00.00 UTC", 86400 在标准UTC天内的秒数.

I have some MATLAB serial date number that I need to use in R but I havt to convert them to a normal date.

    Matlab:
   datestr(733038.6)
    ans =
    27-Dec-2006 14:24:00 

you can see it gives the date and time.

Now we try in R:
Matlab2Rdate <- function(val) as.Date(val - 1, origin = '0000-01-01') 
> Matlab2Rdate(733038.6)
[1] "2006-12-27"

It gives only the date but I need also the time? Any idea

The trick is Matlab uses "January 01, 0000", a fictional reference date, to calculate its date number. The origin of time for the "POSIXct" class in R is, ‘1970-01-01 00:00.00 UTC’. You can read about how different systems handle dates here.

Before converting, you need to account for this difference in reference from one format to another. The POSIX manual contains such an example. Here's my output:

> val<-733038.6
> as.POSIXct((val - 719529)*86400, origin = "1970-01-01", tz = "UTC")
[1] "2006-12-27 14:23:59 UTC"

Where 719529 is ‘1970-01-01 00:00.00 UTC’ in Matlab's datenum and 86400 the number of seconds in an standard UTC day.