How to convert format of time R?

Asked by At

I have a dataframe with the time in the following format:

Time
01.01.2017 01:00
01.01.2017 02:00
01.01.2017 03:00
01.01.2017 04:00 
01.01.2017 05:00 
01.01.2017 06:00

class(df$Time) 
[1] "factor"

Its day, month, year, hours, minutes. I want to convert it into a readable time. I tried this already:

strptime(df$Time, format="%d-%m-%Y  %H:%M")
as.POSIXct(df$Time)

It doesnt work. How can I transform it and change the format to: 2017-01-01 01:00. So I want to have Year, month, day, hours, minutes.

2 Answers

5
Ronak Shah On Best Solutions

Read ?strptime you need the format to be

strptime("01.01.2017 01:00", format="%d.%m.%Y  %H:%M")
#[1] "2017-01-01 01:00:00"

If you need output to be in the particular format we can use format

format(strptime("01.01.2017 01:00", format="%d.%m.%Y  %H:%M"), "%Y-%m-%d  %H:%M")
#[1] "2017-01-01  01:00"

Same would work with as.POSIXct

as.POSIXct("01.01.2017 01:00", format="%d.%m.%Y  %H:%M")

Or to ignore specifying formats directly use lubridate::dmy_hm

lubridate::dmy_hm("01.01.2017 01:00")

One thing to note as mentioned by @42- is although they look the same the output of format is a character value whereas that of as.POSIXct and strptime is a datetime value.

1
akrun On

We can just use anytime

librrary(anytime)
anytime(df$Time)
#[1] "2017-01-01 01:00:00 EST" "2017-01-01 02:00:00 EST" "2017-01-01 03:00:00 EST" "2017-01-01 04:00:00 EST"
#[5] "2017-01-01 05:00:00 EST" "2017-01-01 06:00:00 EST"

NOTE: There are a multiple dupes for this post

Possible dupes of this or this or this

data

df <- structure(list(Time = c("01.01.2017 01:00", "01.01.2017 02:00", 
 "01.01.2017 03:00", "01.01.2017 04:00", "01.01.2017 05:00", 
 "01.01.2017 06:00"
 )), class = "data.frame", row.names = c(NA, -6L))