R:更改timedate< chr>以分开日期< date>和时间< hms>

6kkfgxo0  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(126)

我有一个输出为chr格式的日期列:

glimpse(november$start_at): 
chr [1:337735] "01/11/2022 00:00" "01/11/2022 00:00" "01/11/2022 00:00" "01/11/2022 00:00" "01/11/2022 00:01" "01/11/2022 06:43"

我想把它分成两个独立的日期和时间列。start_date应该是日期格式,而start_time应该是时间(hms)格式。注意,start_at中的时间只有小时和分钟,没有秒,所以我假设11月 Dataframe 中的所有数据的秒都是00。我希望我的输出如下:

start_date  start_Time 
2022/11/01  02:04:00
.
.
.

到目前为止,我已经完成了日期部分:

november$start_date <- as.Date(format(as.Date(november$started_at, format = "%d/%m/%Y"), "%Y-%m-%d"))

str(november$start_date) 
 start_date     : Date[1:337735], format: "2022-11-01" "2022-11-01" "2022-11-01" "2022-11-01"

问题是,当我运行代码的时间,我得到00:00:00的一切或NA的一切。

format(as.POSIXct(november$started_at), format = "%H:%M:%S")

 [1] "00:00:00" "00:00:00" "00:00:00" "00:00:00" "00:00:00" "00:00:00"

as.Date(parse_date_time(november$started_at,"dmy"))

 [1] NA NA NA NA NA NA NA NA NA 

thanks in advanced.
uemypmqf

uemypmqf1#

library(lubridate)
library(tidyverse)

november <- tibble(
  start_at = c(
    "01/11/2022 00:00",
    "01/11/2022 00:00",
    "01/11/2022 00:00",
    "01/11/2022 00:00",
    "01/11/2022 00:01",
    "01/11/2022 06:43"
  )
)

# A tibble: 6 × 1
  start_at        
  <chr>           
1 01/11/2022 00:00
2 01/11/2022 00:00
3 01/11/2022 00:00
4 01/11/2022 00:00
5 01/11/2022 00:01
6 01/11/2022 06:43

改变新列

november %>% 
  mutate(
    start_date = as_date(mdy_hm(start_at)), 
    start_time = as_hms(mdy_hm(start_at))
  )

# A tibble: 6 x 3
  start_at         start_date start_time
  <chr>            <date>     <time>    
1 01/11/2022 00:00 2022-01-11 00:00     
2 01/11/2022 00:00 2022-01-11 00:00     
3 01/11/2022 00:00 2022-01-11 00:00     
4 01/11/2022 00:00 2022-01-11 00:00     
5 01/11/2022 00:01 2022-01-11 00:01     
6 01/11/2022 06:43 2022-01-11 06:43
r1zhe5dt

r1zhe5dt2#

基本上在空间使用strptimestrsplit,但选择第二个元素。

transform(df, x=NULL, date=strptime(x, '%d/%m/%Y %H:%M')) |>
  {\(.) transform(., time=sapply(strsplit(as.character(date), ' '), `[`, 2))}()
#   y                date     time
# 1 0 2022-11-01 00:00:00 00:00:00
# 2 0 2022-11-01 00:00:00 00:00:00
# 3 0 2022-11-01 00:00:00 00:00:00
# 4 0 2022-11-01 00:00:00 00:00:00
# 5 0 2022-11-01 00:01:00 00:01:00
# 6 0 2022-11-01 06:43:00 06:43:00
  • 数据:*
df <- structure(list(x = c("01/11/2022 00:00", "01/11/2022 00:00", 
"01/11/2022 00:00", "01/11/2022 00:00", "01/11/2022 00:01", "01/11/2022 06:43"
), y = c(0, 0, 0, 0, 0, 0)), class = "data.frame", row.names = c(NA, 
-6L))

相关问题