2012-08-28 68 views
6

我正在做一個自動生成記錄數據的實驗。該軟件會生成格式爲41149.014850的時間戳。我想將此小數時間戳轉換爲28.08.2012 00:21:23。我如何在R中最優雅地做到這一點?如何優雅地將datetime從十進制轉換爲「%d。%m。%y%H:%M:%S」?

我嘗試使用函數strsplit以及具有指定原點的函數as.Date以及times函數。但無濟於事。我在將時間戳分成兩個數字時遇到問題,我可以使用功能as.Datetimes訪問這兩個數字。

下面是一些演示代碼:

myDatetime <- c(41149.004641, # 28.08.2012 00:06:41 
41149.009745, # 28.08.2012 00:14:02 
41149.014850, # 28.08.2012 00:21:23 
41149.019954) # 28.08.2012 00:28:44 

## not working out for me 
Dat.char <- as.character(myDatetime) 
date.split <- strsplit(Dat.char, split = "\\.") 
## how to proceed from here, if it is a good way at all 

請讓我還是知道如果您需要了解的挑戰更多的信息,如果我能以更好的方式提出問題。任何搜索都無濟於事。

直接幫助或鏈接到其他網站/職位是非常感謝。

回答

9

您的日期採用類似Excel的日期格式(1900年1月1日以後的天數),因此您需要將它們轉換爲R日期格式。然後您可以將其轉換爲日期時間格式(POSIXct)。

# first convert to R Date 
datetime <- as.Date(myDatetime-1, origin="1899-12-31") 
# now convert to POSIXct 
(posixct <- .POSIXct(unclass(datetime)*86400, tz="GMT")) 
# [1] "2012-08-28 00:06:40 GMT" "2012-08-28 00:14:01 GMT" 
# [3] "2012-08-28 00:21:23 GMT" "2012-08-28 00:28:44 GMT" 
# times are sometimes off by 1 second, add more digits to seconds to see why 
options(digits.secs=6) 
posixct 
# [1] "2012-08-28 00:06:40.9823 GMT" "2012-08-28 00:14:01.9680 GMT" 
# [3] "2012-08-28 00:21:23.0399 GMT" "2012-08-28 00:28:44.0256 GMT" 
# round to nearest second 
(posixct <- round(posixct, "sec")) 
# [1] "2012-08-28 00:06:41 GMT" "2012-08-28 00:14:02 GMT" 
# [3] "2012-08-28 00:21:23 GMT" "2012-08-28 00:28:44 GMT" 
# now you can convert to your desired format 
format(posixct, "%d.%m.%Y %H:%M:%S") 
# [1] "28.08.2012 00:06:41" "28.08.2012 00:14:02" 
# [3] "28.08.2012 00:21:23" "28.08.2012 00:28:44" 
2

此靠攏:數字顯示,自接近1/1/1900日期的秒數:

as.POSIXct(x*3600*24, origin=as.Date("1900-01-01")-2, tz="UTC") 
[1] "2012-08-28 01:06:40 BST" "2012-08-28 01:14:01 BST" "2012-08-28 01:21:23 BST" 
[4] "2012-08-28 01:28:44 BST" 

目前仍然是一個時區中存在偏差。

相關問題