Converting date and time extraction

Want to change the class for Time to POSIXlt and extract only hours minutes and seconds

str(df3$Time)
chr [1:2075259] "17:24:00" "17:25:00" "17:26:00" "17:27:00" ...

      

The strptime function is used

df33$Time <- strptime(df3$Time, format = "%H:%M:%S") 

      

This is the date / time added

> str(df3$Time)
 POSIXlt[1:2075259], format: "2015-08-07 17:24:00" "2015-08-07 17:25:00" "2015-08-07 17:26:00" ..

      

...

You want to extract only the time without changing the POSIXlt class. using strftime function

df3$Time <- strftime(df3$Time, format = "%H:%M:%S") 

      

but this will convert the class back to "char" -

> class(df3$Time)
[1] "character"

      

How can I simply extract the time using a set of classes in POSIX or numeric ...

+3


source to share


4 answers


If your data

a <- "17:24:00"

b <- strptime(a, format = "%H:%M:%S")

      

you can use lubridate

to get the result of the classinteger

library(lubridate)
hour(b)
minute(b)

# > hour(b)
# [1] 17
# > minute(b)
# [1] 24


# > class(minute(b))
# [1] "integer"

      



and you can combine them with

# character
paste(hour(b),minute(b), sep=":")

# numeric
hour(b) + minute(b)/60

      

eg.

I would not recommend doing this if you want to do further operations on your data. However, it can be convenient to do this if you want to plot the results.

+6


source


The datetime object contains the date and time; you cannot extract "just time". Therefore, you need to think about what you want:

  • POSIXlt - Datetime representation (as a list of components)
  • POSIXct is another representation of Datetime (as compact number)


None of these are missing the Date part. When you have a valid object, you can choose to display only the time. But you cannot make the Date part disappear from the view.

+4


source


If you want it in POSIX format, the only way is to leave it as it is and only fetch it part of the time each time you show it. But internally it will always be date + time. However, if you want it to be numeric, you can simply convert it to a number. For example, to get the time as the number of seconds elapsed since the beginning of the day:

df3$Time=df3$Time$sec + df3$Time$min*60 + df3$Time$hour*3600

      

0


source


You can also use a package chron

to fetch just a different day:

library(chron) 

# current date/time in POSIXt format as an example
timenow <- Sys.time()

# create chron object "times"
onlytime <- times(strftime(timenow,"%H:%M:%S"))

> onlytime
[1] 14:18:00
> onlytime+1/24
[1] 15:18:00
> class(onlytime)
[1] "times"

      

0


source







All Articles