Converting from "POSIXct" "POSIXt" class to character not working

I'm trying to convert time in R to a character string, but I'm getting very weird and inconsistent results. Both df1 and df2 "time" variables are of the same class and timezone, but when I try to convert df1 to character R adds 1900 to the military time

> class(df1$time)
[1] "POSIXct" "POSIXt"

> print(head(df1$time))
[1] "1899-12-31 00:00:00 UTC" "1899-12-31 00:15:00 UTC" "1899-12-31 00:30:00 UTC"
[4] "1899-12-31 00:45:00 UTC" "1899-12-31 01:00:00 UTC" "1899-12-31 01:15:00 UTC"

df1$miltime <- strftime(df1$time, "%H%M")

> print(head(df1$miltime))
[1] "1900" "1915" "1930" "1945" "2000" "2015"

#####################################################################

df2 <- data.frame(time = as.POSIXct(c("1899-12-31 00:00:00 UTC", 
                                     "1899-12-31 00:15:00 UTC",
                                     "1899-12-31 00:30:00 UTC",
                                     "1899-12-31 00:45:00 UTC",
                                     "1899-12-31 01:00:00 UTC", 
                                     "1899-12-31 01:15:00 UTC")))

df2$mltime <- strftime(df2$time, "%H%M") 
print(df2)

> print(df2) 
                 time mltime
1 1899-12-31 00:00:00   0000
2 1899-12-31 00:15:00   0015
3 1899-12-31 00:30:00   0030
4 1899-12-31 00:45:00   0045
5 1899-12-31 01:00:00   0100
6 1899-12-31 01:15:00   0115

I don't understand why, but this works!

df1$miltime <- sapply(strsplit(as.character(df1$time) , " ") , function(x) {
  s <- x[[2]]
  s <- strsplit(s , ":")
  sapply(s , function(x) paste0(x[1],x[2]))
})

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.