structure(list(Datetime = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "2016-10-19 00:00:00", class = "factor")), .Names = "Datetime", row.names = c(NA,
-6L), class = "data.frame")
当我尝试将Datetime转换为POSIXct时:
t$Datetime<-as.POSIXct(t$Datetime, format="%Y-%m-%d %H:%M:%S")
我从数据中丢失了小时,分钟和秒。它变成这样:
Datetime
1 2016-10-19
2 2016-10-19
3 2016-10-19
4 2016-10-19
5 2016-10-19
6 2016-10-19
dput(t)
structure(list(Datetime = structure(c(1476849600, 1476849600,
1476849600, 1476849600, 1476849600, 1476849600), class = c("POSIXct",
"POSIXt"), tzone = "")), .Names = "Datetime", row.names = c(NA,
-6L), class = "data.frame")
为什么我要从数据中丢失小时,分钟?
答案 0 :(得分:-1)
你没有失去它,它们只是没有显示(因为00:00:00意味着没有重要的时间)。尝试设置小时,分钟和秒的值,它们将会显示。
t <- structure(list(
Datetime = structure(c(1L, 1L, 1L, 1L, 1L, 1L),
.Label = "2016-10-19 00:00:00",
class = "factor")),
.Names = "Datetime",
row.names = c(NA, -6L),
class = "data.frame")
t$Datetime <- as.POSIXct(t$Datetime, format="%Y-%m-%d %H:%M:%S")
head(t, 3)
# Datetime
# 1 2016-10-19 01:01:01
# 2 2016-10-19 01:01:01
# 3 2016-10-19 01:01:01
str(t)
#'data.frame': 6 obs. of 1 variable:
# $ Datetime: POSIXct, format: "2016-10-19 01:01:01" "2016-10-19 01:01:01" ...
我建议使用lubridate包来管理日期,它易于使用且不易出错。以下代码给出了相同的结果。
library(lubridate)
t$Datetime <- ymd_hms(t$Datetime)