无法将日期时间列转换为字符

时间:2019-01-22 22:46:21

标签: r date time posixct

head(my_df)
# A tibble: 6 x 5

     ID Name               Type  Function   Date_time          
  <dbl> <chr>              <chr> <chr>      <dttm>       

1     1 Look Away          1v3   teg        1899-12-31 00:00:43
2     1 Bobsled Run        2v2   teg        1899-12-31 00:01:32
3     1 Give me a Break!   item  additional 1899-12-31 00:00:20
4     1 Shock Drop or Roll 3v1   teg        1899-12-31 00:00:23
5     1 Move to the Music  3v1   teg        1899-12-31 00:00:47
6     1 Bowl Over          3v1   teg        1899-12-31 00:00:41

我试图将Date_time列分为两列:Date和Time。

首先,我尝试使用以下方法将两者分开:

my_df %>% separate(“Date_time”, into = c("Date", "Time"), sep = " = ")

但是它都变成了字符向量,这意味着我不能添加/使用内容。

我四处查看堆栈溢出,发现此解决方案可提取时间,但它也将新列转换为字符。这是代码:

head(my_df)

# A tibble: 6 x 5
     ID Name               Type  Function   Date_time          
  <dbl> <chr>              <chr> <chr>      <dttm>             
1     1 Look Away          1v3   teg        1899-12-31 00:00:43
2     1 Bobsled Run        2v2   teg        1899-12-31 00:01:32
3     1 Give me a Break!   item  additional 1899-12-31 00:00:20
4     1 Shock Drop or Roll 3v1   teg        1899-12-31 00:00:23
5     1 Move to the Music  3v1   teg        1899-12-31 00:00:47
6     1 Bowl Over          3v1   teg        1899-12-31 00:00:41

> my_df$Time <- format(as.POSIXct(my_df$Date_time), format = "%H:%M:%S")
> head(my_df)
# A tibble: 6 x 6
    ID Name               Type  Function   Date_time           Time    
  <dbl> <chr>              <chr> <chr>      <dttm>              <chr>   
1     1 Look Away          1v3   teg        1899-12-31 00:00:43 00:00:43
2     1 Bobsled Run        2v2   teg        1899-12-31 00:01:32 00:01:32
3     1 Give me a Break!   item  additional 1899-12-31 00:00:20 00:00:20
4     1 Shock Drop or Roll 3v1   teg        1899-12-31 00:00:23 00:00:23
5     1 Move to the Music  3v1   teg        1899-12-31 00:00:47 00:00:47
6     1 Bowl Over          3v1   teg        1899-12-31 00:00:41 00:00:41

如您所见,新的“时间”列现在是一个字符向量。在保持dttm(或最好只是时间对象)的同时如何做

谢谢

吉姆

0 个答案:

没有答案