fifthace
fifthace

Reputation: 546

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

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

Upvotes: 6

Views: 15885

Answers (3)

vpz
vpz

Reputation: 1044

Well I had the same problem.

One way that I found to solve that was changing to GMT my Timezone in tz="GMT":

as.POSIXct(x = c("2013-03-31 02:05:00"),
           format="%Y-%m-%d %H:%M:%S",
           tz="GMT"
)

# [1] "2013-03-31 02:05:00 GMT"

Upvotes: 0

James
James

Reputation: 66844

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

Upvotes: 15

Prasanna Nandakumar
Prasanna Nandakumar

Reputation: 4335

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"

Upvotes: 0

Related Questions