Converting datetime-format into hours, minutes,seconds format

Hello I am quite new with R and need some help.

I have a lot of different dataframes with different informations, but all have in common a column with Datetime (2021-10-9 01:35:12). But I just need the information about hours, minute and seconds to work with....

I tried to to change the time format with: as.POSIXct((df$time), format = "%H:%M:%S") but this does not change anything.... Because I just started with r and don't know all the functions, can you help me? Is there any function for maybe extract just the H:M:S out of a datetime format?

Tx a lot you will save me a lot of time! Otherwise I have to do it manually

Hi @Agrarstudent ,
For this you should use the lubridate library.
If not installed on your machine, run this before: install.packages("lubridate")

Then run this:

library(lubridate)
example_date <- "2021-10-9 01:35:12"
hour(example_date )
#> 1
minute(example_date )
#> 35
second(example_date )
#> 12

Check the cheatsheet here to have an overview of what it does.

I believe xvalda has a typo in the example

example_date <- "2021-10-9 01:35:12"

should read

example_date <- ymd_hms("2021-10-9 01:35:12")

indeed, thanks for correcting @jrkrideau

Even though these lubridate functions (hour() , minute(), ...) work on a character objects formatted as date-time, it is important to parse them in the proper POSIXt format as a first step.

Thanks for spotting this.

Hello @xvalda

Tx for your answer! I have no clue what I did but it works.... :sweat_smile:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.