Lorcan Treanor
Lorcan Treanor

Reputation: 561

Converting a character to a Date Time format in R

Don't know what I'm doing wrong here. Am trying to convert a character to a POSIXct date format and getting a null. Here is some sample code:

as.POSIXct(strptime("29-MAR-2015 01:14:32", format = "%d-%b-%Y %H:%M:%S"))

which gives me a NA.

The previous date was in March. If I switch the date to April, and repeat the same process, this is the result I get::

as.POSIXct(strptime("29-APR-2015 01:14:32", format = "%d-%b-%Y %H:%M:%S"))

I get: "2015-04-29 01:14:32 IST"

Why does this conversion work for the March date, but not the April date?

Upvotes: 1

Views: 142

Answers (1)

rbatt
rbatt

Reputation: 4807

You don't need the strptime. E.g., try:

as.POSIXct("29-APR-2015 01:14:32", format = "%d-%b-%Y %H:%M:%S")

[1] "2015-04-29 01:14:32 EDT"

Of course, I'm in different time zone.

One thing to keep in mind, is that certain times don't exist in certain time zones due to "daylight savings time" and the like – for example, clocks will "leap" forward or backwards 1 hour; the latter case isn't problematic in your case (but confusing b/c an hour is repeated); the previous case produces a problem because an hour is skipped!

How to solve? Specify a time zone that doesn't have daylight savings time. E.g., GMT:

as.POSIXct("29-MAR-2015 01:14:32", format = "%d-%b-%Y %H:%M:%S", tz="GMT")

[1] "2015-03-29 01:14:32 GMT"

Note: I can't reproduce your IST time zone, so this is really just my best guess. Try using tz="GMT", or specify the actual time zone of the date (rather than relying on local time zone), and that should help!

Also explains why others can't reproduce easily.

Upvotes: 2

Related Questions