Krug
Krug

Reputation: 1013

Change time format in R (POSIXlt)

I have a 4x2 data frame where one of the columns contains DateTime stamps. The DateTime is in the following format: %Y-%m-%d %H:%M:%S. I need to format the DateTime as POSIXlt, and I do not want seconds to show. The code below formats as POSIXlt, but somehow seconds are still showing. How can I get rid of the seconds? Thank you very much.

DATS <- structure(list(DateTime = c("2016-04-25  23:59:00", "2016-04-25  23:58:00","2016-04-25  23:57:00", "2016-04-25  23:56:00"), Last = c(42.84,42.84, 42.85, 42.85)), .Names = c("DateTime", "Last"), row.names = c(NA,4L), class = "data.frame") 
DATS$DateTime <- strptime(DATS$DateTime, format = "%Y-%m-%d %H:%M")

#Output for DATS after running code
              DateTime  Last
1 2016-04-25  23:59:00 42.84
2 2016-04-25  23:58:00 42.84
3 2016-04-25  23:57:00 42.85
4 2016-04-25  23:56:00 42.85

Upvotes: 1

Views: 151

Answers (1)

James Ferr&#233;
James Ferr&#233;

Reputation: 48

As other have answered, the seconds will need to be included. As an example, note if I remove ":%S" and change the seconds from 00 to various numbers, the seconds are still included but rounded down to 00.

    DATS <- structure(list(DateTime = c("2016-04-25  23:59:15", "2016-04-25  23:58:30","2016-04-25  23:57:45", "2016-04-25  23:56:59"), Last = c(42.84,42.84, 42.85, 42.85)), .Names = c("DateTime", "Last"), row.names = c(NA,4L), class = "data.frame") 

DATS$DateTime <- strptime(DATS$DateTime, format = "%Y-%m-%d %H:%M:%S")
DATS

             DateTime  Last
1 2016-04-25 23:59:15 42.84
2 2016-04-25 23:58:30 42.84
3 2016-04-25 23:57:45 42.85
4 2016-04-25 23:56:59 42.85

DATS$DateTime <- strptime(DATS$DateTime, format = "%Y-%m-%d %H:%M")
DATS

             DateTime  Last
1 2016-04-25 23:59:00 42.84
2 2016-04-25 23:58:00 42.84
3 2016-04-25 23:57:00 42.85
4 2016-04-25 23:56:00 42.85

Upvotes: 1

Related Questions