Date time conversion and extract only time

匆匆过客 提交于 2019-11-29 01:28:12

If your data is

a <- "17:24:00"

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

you can use lubridate in order to have a result of class integer

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

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


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

and you can combine them using

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

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

for instance.

I would not advise to do that if you want to do any further operations on your data. However, it might be convenient to do that if you want to plot the results.

A datetime object contains date and time; you cannot extract 'just time'. So you have to think throught what you want:

  • POSIXlt is a Datetime representation (as a list of components)
  • POSIXct is a different Datetime representation (as a compact numeric)

Neither one omits the Date part. Once you have a valid object, you can choose to display only the time. But you cannot make the Date part disappear from the representation.

You can also use the chron package to extract just times of the 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"

This is my idiom for getting just the timepart from a datetime object. I use floor_date() from lubridate to get midnight of the timestamp and take the difference of the timestamp and midnight of that day. I create and store a hms object provided with lubridate (I believe) in dataframes because the class has formatting of hh:mm:ss that is easy to read, but the underlying value is a numeric value of seconds. Here is my code:

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

# Create timestamps
#
# Get timepart by subtacting the timestamp from it's floor'ed date, make sure
# you convert to seconds, and then cast to a time object provided by the
# `hms` package.
# See: https://www.rdocumentation.org/packages/hms/versions/0.4.2/topics/hms
dt <- tibble(dt=c("2019-02-15T13:15:00", "2019-02-19T01:10:33") %>% ymd_hms()) %>%
  mutate(timepart = hms::hms(as.numeric(dt - floor_date(dt, "1 day"), unit="secs")))

# Look at result
print(dt)
#> # A tibble: 2 x 2
#>   dt                  timepart
#>   <dttm>              <time>  
#> 1 2019-02-15 13:15:00 13:15   
#> 2 2019-02-19 01:10:33 01:10

# `hms` object is really a `difftime` object from documentation, but is made into a `hms`
# object that defaults to always store data in seconds.
dt %>% pluck("timepart") %>% str()
#>  'hms' num [1:2] 13:15:00 01:10:33
#>  - attr(*, "units")= chr "secs"

# Pull off just the timepart column
dt %>% pluck("timepart")
#> 13:15:00
#> 01:10:33

# Get numeric part.  From documentation, `hms` object always stores in seconds.
dt %>% pluck("timepart") %>% as.numeric()
#> [1] 47700  4233

Created on 2019-02-15 by the reprex package (v0.2.1)

If you want it in POSIX format, the only way would be to leave it as it is, and extract just the "time" part everytime you display it. But internally it will always be date + time anyway. If you want it in numeric, however, you can simply convert it into a number. For example, to get time as number of seconds passed since the beginning of the day:

df3$Time=df3$Time$sec + df3$Time$min*60 + df3$Time$hour*3600
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!