删除时间戳的结尾

Remove end of timestamp

我有一个时间戳向量"+00"我想删除

> test
[1] "2018-01-02 06:40:00+00" "2018-01-02 06:50:00+00" "2018-01-02 07:00:00+00"
[4] "2018-01-02 07:10:00+00" "2018-01-02 07:20:00+00" "2018-01-02 07:30:00+00"

他们已经在角色中了 class

> class(test)
[1] "character"

我已经申请了gsub()

> gsub("+.*","",test)
[1] "" "" "" "" "" ""

但这并没有提供所需的输出——我做错了什么?

dput(test)
c("2018-01-02 06:40:00+00", "2018-01-02 06:50:00+00", "2018-01-02 07:00:00+00", 
"2018-01-02 07:10:00+00", "2018-01-02 07:20:00+00", "2018-01-02 07:30:00+00")

您可以提取除 +00 之外的所有内容。使用 $ 使正则表达式适合字符串的最后一部分。

> gsub("(^.*)\+00$", "\1", x) # extract everything between ()
[1] "2018-01-02 06:40:00" "2018-01-02 06:50:00" "2018-01-02 07:00:00"
[4] "2018-01-02 07:10:00" "2018-01-02 07:20:00" "2018-01-02 07:30:00"

如果字符数相同,就用substr:

test <- c("2018-01-02 06:40:00+00", "2018-01-02 06:50:00+00", "2018-01-02 07:00:00+00")

nchar(test)
# [1] 22 22 22

substr(test, 1, 19)
# [1] "2018-01-02 06:40:00" "2018-01-02 06:50:00" "2018-01-02 07:00:00"

或使用 gsub with fixed = TRUE:

gsub("+00", "", test, fixed = TRUE)
# [1] "2018-01-02 06:40:00" "2018-01-02 06:50:00" "2018-01-02 07:00:00"

您可以通过首先将字符向量转换为 POSIXct 元素,然后再将其转换回字符来解决此问题。

> test <- c("2018-01-02 06:40:00+00","2018-01-02 06:50:00+00","2018-01-02   07:00:00+00")
> test_date <- as.POSIXct(test, format = "%Y-%m-%d %H:%M:%S")
> test_char <- as.character(test_date)
> test_char
[1] "2018-01-02 06:40:00" "2018-01-02 06:50:00" "2018-01-02 07:00:00"

优点是可以自由修改时间戳的语法:

> test_char_2 <- as.character(format(test_date, "%m/%d/%y %H:%M:%S"))
> test_char_2
[1] "01/02/18 06:40:00" "01/02/18 06:50:00" "01/02/18 07:00:00"