R convert dataframe string column to datetime with one-digit length hour

ragesz picture ragesz · Aug 9, 2016 · Viewed 7.1k times · Source

How can I convert a "string" dataframe column attr_date into datetime when my hour can be one digit length too (eg.: 2012.01.01 9:00:00)? The following code returns only with the date part without time part:

df[['attr_date']] <- as.Date(df[['attr_date']], format='%Y.%m.%d  %H:%M:%S')

So the result of 2012.01.01 9:00:00 is 2012-01-01.

Bonus question: Using Anaconda R Essentials, in Jupyter R Notebook why I get 15340.00 as the result of 2012.01.01 9:00:00 when I use the above code?

Thank you!

Answer

Matt Sandgren picture Matt Sandgren · Aug 9, 2016

Try using strptime instead:

df[['attr_date']] <- strptime(df[['attr_date']], format='%Y.%m.%d  %H:%M:%S')