向日期时间添加分隔符
Adding separator to dateTime
我有一个以日期为字符的向量
x <- "2015-02-01 09:05:23"
我想将其转换为 dateTime 对象
x <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
然后 "T" 作为日期和时间之间的分隔符(参见 XML Schema)以获得以下输出
"2015-02-01T09:05:23"
如何将 "T" 分隔符放入字符串中?
x <- "2015-02-01 09:05:23"
d <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
w <- substr(weekdays(d),1,1) # 1,1 selects the first letter of the day
y <- paste0(strsplit(as.character(d)," ")[[1]][1],w,strsplit(as.character(d)," ")[[1]][2])
y
[1] "2015-02-01S09:05:23"
如果你只想写一个 T
:
paste0(strsplit(as.character(d)," ")[[1]][1],'T',strsplit(as.character(d)," ")[[1]][2])
[1] "2015-02-01T09:05:23"
您可以使用format
函数获取角色对象。
x <- "2015-02-01 09:05:23"
format(as.POSIXct(x, "GMT"), "%FT%T")
#[1] "2015-02-01T09:05:23"
在这种情况下,您可以使用 gsub
将 space 替换为 T
x <- "2015-02-01 09:05:23"
x <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
gsub(" ", "T", x)
#[1] "2015-02-01T09:05:23"
根据@Avinash Raj 的评论,在这种情况下仅使用 sub
就足够了。
sub(" ", "T", x)
#[1] "2015-02-01T09:05:23"
我有一个以日期为字符的向量
x <- "2015-02-01 09:05:23"
我想将其转换为 dateTime 对象
x <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
然后 "T" 作为日期和时间之间的分隔符(参见 XML Schema)以获得以下输出
"2015-02-01T09:05:23"
如何将 "T" 分隔符放入字符串中?
x <- "2015-02-01 09:05:23"
d <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
w <- substr(weekdays(d),1,1) # 1,1 selects the first letter of the day
y <- paste0(strsplit(as.character(d)," ")[[1]][1],w,strsplit(as.character(d)," ")[[1]][2])
y
[1] "2015-02-01S09:05:23"
如果你只想写一个 T
:
paste0(strsplit(as.character(d)," ")[[1]][1],'T',strsplit(as.character(d)," ")[[1]][2])
[1] "2015-02-01T09:05:23"
您可以使用format
函数获取角色对象。
x <- "2015-02-01 09:05:23"
format(as.POSIXct(x, "GMT"), "%FT%T")
#[1] "2015-02-01T09:05:23"
在这种情况下,您可以使用 gsub
x <- "2015-02-01 09:05:23"
x <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
gsub(" ", "T", x)
#[1] "2015-02-01T09:05:23"
根据@Avinash Raj 的评论,在这种情况下仅使用 sub
就足够了。
sub(" ", "T", x)
#[1] "2015-02-01T09:05:23"