Thales Marques Thales Marques - 1 year ago 118
R Question

R strptime to 00h00 Format

How can I strptime a character like "15/09/2016 20h26"?

I searched this on the strptime official manual and arround the Stack overflow, but I didn't find anything that could help me.

I tried this code:

u <- ("15/09/2016 20h26")
strptime(u, format = "%d/%m/%Y %H:%M")


strptime(u, format = "%d/%m/%Y %H'h'%M")

Anyone has any idea of what I need to do?


Firstly, sorry for the clearness of the question.

I tried to use a sample to describe my problem, but it seems like a typo.

I have a txt file with 400 observations of time in the format "20/01/2016 14h00". I'm trying to convert this to date with strptime:

here is my code:

y <- read.table('materias_data.txt', sep = ";")
l <- strptime(y, format = "%d/%m/%Y %Hh%M")

I got this error when I run the code:

Error in strptime(y, format = "%d/%m/%Y %Hh%M") : input string is
too long

What can I do to convert correctly the data.frame?

Edit 2: Solution

Reading the comments I realized what the problem is:

strptime doesn't work to data.frame but it works on characters.

The step to solve this is

y <- read.table('materias_data.txt', sep = ";")
l <- strptime(y[,1], format = "%d/%m/%Y %Hh%M")
df <- data.frame(l)

Thank You

Answer Source

The relatively new anytime package I added to CRAN parses this automatically without extra help:

R> anytime("15/09/2016 20h26")
[1] "2016-09-15 20:26:00 CDT"

Another nice feature is that it also automatically converts from factor (or ordered) to character.

So if you have a data.frame df with a column of values like this in, say, a column called datestr then just pass the column:

R> anytime( df[, "datestr"] )

which you can assign to a new column in the data.frame as well:

R> df[, "parsedtime"] <- anytime( df[, "datestr"] )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download