How to change date format to 2019-Feb-07 to 2019-02-07 in R?

0

Issue

I have a code that reads in data from a .txt file, in which there is a date column dd/mm/yyyy and time column HH:MM:SS and I want to merge the columns into one date time column yyyy/mm/dd HH:MM:SS.

The data frame structure is:

structure(list(V1 = c("05/02/2019", "07/02/2019", "08/02/2019", 
"09/02/2019", "10/02/2019", "11/02/2019", "12/02/2019", "13/02/2019"
),
V2 = c("10:37:34", "00:00:00", "00:00:00", "00:00:00", "00:00:00", 
"00:00:00", "00:00:00", "00:00:00"), 
V3 = c("0,2", "0", "0", 
"0", "0", "0", "0", "0"), 
V4 = c("NEW-BLOCK", "NEW-DAY", "NEW-DAY", 
"NEW-DAY", "NEW-DAY", "NEW-DAY", "NEW-DAY", "NEW-DAY"), 
V5 = c("", 
"", "", "", "", "", "", ""), 
V6 = c("", "", "", "", "", "", "", 
"")), row.names = 5:12, class = "data.frame")

My working code is:

importeddataframe <-read.table(k,fill =TRUE, stringsAsFactors =FALSE )

importeddataframe$V1<-chron(importeddataframe$V1, importeddataframe$V2, format =c(dates="d/m/y", times="h:m:s"))
importeddataframe$V1<-chron(importeddataframe$V1, importeddataframe$V2, format =c(dates="yyyy-mm-dd", times="H:M:S"))

where k is the path source, V1 is the date column, V2 is the time column, and I am trying to redefine V1 as a datetime column using chron. I managed to set up the correct format for the dates and times except for one detail: the month is always an abbreviation rather than a number. So February would be Feb instead of 02, October would be Oct instead of 10, etc.

Is there a parameter I need to change in the chron function? Is there another function that doesn’t create a written abbreviation for time?

Thank you for all the help!

Solution

Using chron:

importeddataframe$V1<-chron::chron(importeddataframe$V1, importeddataframe$V2, format =c(dates="d/m/y", times="h:m:s"), out.format=c(dates="y-m-d", times="H:M:S"))
> importeddataframe$V1
[1] (19-02-05 10:37:34) (19-02-07 00:00:00) (19-02-08 00:00:00) (19-02-09 00:00:00) (19-02-10 00:00:00) (19-02-11 00:00:00) (19-02-12 00:00:00)
[8] (19-02-13 00:00:00)

Using base R

importeddataframe$Time <- as.POSIXct(paste(importeddataframe$V1,importeddataframe$V2), format="%d/%m/%Y %H:%M:%S" )
> importeddataframe$Time
[1] "2019-02-05 10:37:34 CET" "2019-02-07 00:00:00 CET" "2019-02-08 00:00:00 CET" "2019-02-09 00:00:00 CET" "2019-02-10 00:00:00 CET"
[6] "2019-02-11 00:00:00 CET" "2019-02-12 00:00:00 CET" "2019-02-13 00:00:00 CET"

Answered By – JKupzig

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More