Using as.POSIXct in R giving na for identical character structures

99封情书 提交于 2020-01-02 04:29:07

问题


I have two timestamps in character form that I want to convert to a POSIX format in R. The timestamps are:

1: "2013-03-30 17:45:00"

2: "2013-03-31 02:05:00"

The first one converts fine, the second one gives me NA. The timestamps are downloaded as characters from an SQL server. Anyone have any ideas what is going wrong?

I don't have the reputation to attach a screenshot, so a screenshot of my R console showing the result is provided here: http://emillarsen.com/r%20console.jpg


回答1:


It looks like a DST issue. I assume from your name you are from Sweden or thereabouts. There was no time in Sweden between 2am and 3am on the 31st March 2013, as the clocks went forward then.

as.POSIXct("2013-03-31 02:05:00",format="%Y-%m-%d %H:%M:%S", tz="Europe/Stockholm")
[1] NA

This is true for anyone on Central European Time (CET).




回答2:


Its working for me. As people in the forum commented -might be TimeZone issues. However i have added ways of doing it.
one way of converting character value to POSIXct:

  dates <- c("1992-02-27", "1992-02-27", "1992-01-14", "1992-02-28", "1992-01-02")
  times <- c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26")
  X <- paste(dates, times)

  str(x)
  chr [1:5] "1992-02-27 23:03:20" "1992-02-27 22:29:56" ...

  dt <- strptime(x, "%Y-%m-%d %H:%M:%S")
  dt
[1] "1992-02-27 23:03:20" "1992-02-27 22:29:56" "1992-01-14 01:03:30"
[4] "1992-02-28 18:21:03" "1992-01-02 16:56:26"  

  str(dt) 
  POSIXlt[1:5], format: "1992-02-27 23:03:20" "1992-02-27 22:29:56" ...  

Another Way: as you approached

> now <- Sys.time()
> now
[1] "2014-01-16 16:58:23 IST"
> as.POSIXlt(as.character(now),tz="GMT")
[1] "2014-01-16 17:05:24 GMT"
> str(as.POSIXlt(now))
 POSIXlt[1:1], format: "2014-01-16 16:58:23"
> unclass(as.POSIXlt(now))
$sec
[1] 23.1636

$min
[1] 58

$hour
[1] 16

$mday
[1] 16

$mon
[1] 0

$year
[1] 114

$wday
[1] 4

$yday
[1] 15

$isdst
[1] 0

attr(,"tzone")
[1] ""    "IST" "IST"


来源:https://stackoverflow.com/questions/21160094/using-as-posixct-in-r-giving-na-for-identical-character-structures

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