简体   繁体   中英

Split given timestamp into year month day period format

I am writing a R code and I have a problem to split Date format into year, month, day, hour format. I have dataframe named Metadata has a column X_date , contains timestamp like '01.01.2020 00:00:00', '01.01.2020 01:00:00' and so on. I want to change this x_date column into additional four columns namely year , month , day and hour . I tried this way using some previous answer:
Metadata$Date <- as.Date(Metadata$X_date)

Metadata$Time <- format(as.POSIXct(Metadata$X_date) ,format = "%Y:%m:%d %H")

It gave me this error: Error in as.POSIXlt.character(as.character(x), ...) : character string is not in a standard unambiguous format

I am very new to R programming. Please help me. Thnak you for your time.

The format specified should match the order in which all the components of 'Date/Time' occurs in the original vector. Assuming that 'day' is first, followed by 'month', the coversion in 'POSIXct' would be

as.POSIXct(Metadata$X_date, format = "%d.%m.%Y %H:%M:%S")

As we want to create new columns, this can be done with tidyverse

library(tidyverse)
library(lubridate)
Metadata %>%
    mutate(X_date = dmy_hms(X_date), 
            year = year(X_date), 
            month = month(X_date),
            day = day(X_date), 
            hour = hour(X_date))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM