通过删除字符的某些部分将列转换为日期时间
Convert a column to datetime by removing certain parts of characters
我有一个如下所示的 df,我正在尝试将 datettime 列转换为 datetime 格式。
ID <- c("A","A","B","B")
datettime <- c("2015-12-03T13:04:06-06:00","2015-12-03T13:54:06-06:00","2015-12-03T16:04:06-06:00","2015-12-03T19:54:06-06:00")
df <- data.frame(ID,datettime)
我的数据集中的 datettime 列是一个字符。我正在尝试将其转换为日期时间格式,但无法正确处理。
library(lubridate)
df$datettime <- ymd_hms(df$datettime)
#The problem here is the hours,minutes and seconds get messed up.
df$datettime <- as.POSIXct(df$datettime,format="%Y%m%d %H%M%S")
#This just ouputs NA's in the column
我想要的输出是
ID datettime
1 A 2015-12-03 13:04:06
2 A 2015-12-03 13:54:06
3 B 2015-12-03 16:04:06
4 B 2015-12-03 19:54:06
如有任何帮助,我们将不胜感激。
您忘记在日期的分隔符之间添加破折号和冒号。这将为您提供所需的输出。
# original code from above:
ID <- c("A","A","B","B")
datettime <- c("2015-12-03T13:04:06-06:00","2015-12-03T13:54:06-06:00","2015-12-03T16:04:06-06:00","2015-12-03T19:54:06-06:00")
df <- data.frame(ID,datettime)
# convert to a POSIXct object
df$datettime <- as.POSIXct(df$datettime,format="%Y-%m-%dT%H:%M:%S")
df
ID datettime
1 A 2015-12-03 13:04:06
2 A 2015-12-03 13:54:06
3 B 2015-12-03 16:04:06
4 B 2015-12-03 19:54:06
也试试这个:
df$datettime <- paste(substr(df$datettime,0,10),substr(df$datettime,12,19))
library(lubridate)
df$datettime <- ymd_hms(df$datettime)
我有一个如下所示的 df,我正在尝试将 datettime 列转换为 datetime 格式。
ID <- c("A","A","B","B")
datettime <- c("2015-12-03T13:04:06-06:00","2015-12-03T13:54:06-06:00","2015-12-03T16:04:06-06:00","2015-12-03T19:54:06-06:00")
df <- data.frame(ID,datettime)
我的数据集中的 datettime 列是一个字符。我正在尝试将其转换为日期时间格式,但无法正确处理。
library(lubridate)
df$datettime <- ymd_hms(df$datettime)
#The problem here is the hours,minutes and seconds get messed up.
df$datettime <- as.POSIXct(df$datettime,format="%Y%m%d %H%M%S")
#This just ouputs NA's in the column
我想要的输出是
ID datettime
1 A 2015-12-03 13:04:06
2 A 2015-12-03 13:54:06
3 B 2015-12-03 16:04:06
4 B 2015-12-03 19:54:06
如有任何帮助,我们将不胜感激。
您忘记在日期的分隔符之间添加破折号和冒号。这将为您提供所需的输出。
# original code from above:
ID <- c("A","A","B","B")
datettime <- c("2015-12-03T13:04:06-06:00","2015-12-03T13:54:06-06:00","2015-12-03T16:04:06-06:00","2015-12-03T19:54:06-06:00")
df <- data.frame(ID,datettime)
# convert to a POSIXct object
df$datettime <- as.POSIXct(df$datettime,format="%Y-%m-%dT%H:%M:%S")
df
ID datettime
1 A 2015-12-03 13:04:06
2 A 2015-12-03 13:54:06
3 B 2015-12-03 16:04:06
4 B 2015-12-03 19:54:06
也试试这个:
df$datettime <- paste(substr(df$datettime,0,10),substr(df$datettime,12,19))
library(lubridate)
df$datettime <- ymd_hms(df$datettime)