I have the following data. order.time is integer format. How to I convert it into time format, without adding date?
order.time
9:58:58
9:58:26
9:56:28
9:56:18
9:56:12
I have tried using parse_date_time, strptime, but all the functions add date and time zone in the final data. I only want to convert time from integer format to a format where I can draw plots with time in the x-axis
In the tidyverse, the hms package provides an S3 class for time of day:
> time <- hms::as_hms(c("9:58:58", "9:58:26", "9:56:28", "9:56:18", "9:56:12"))
> time
09:58:58
09:58:26
09:56:28
09:56:18
09:56:12
> class(time)
[1] "hms" "difftime"
> str(time)
'hms' num [1:5] 09:58:58 09:58:26 09:56:28 09:56:18 ...
- attr(*, "units")= chr "secs"
The function as_hms() also takes integer arguments, but only in seconds:
> (time_in_hours <- c(6, 9, 12))
[1] 6 9 12
> hms::as_hms(time_in_hours * 3600)
06:00:00
09:00:00
12:00:00
I would check out the anytime package. It works almost all of the time.
library(anytime)
order.time <- anytime(order.time)
Use as.POSIXct():
times <- as.POSIXct(c('9:58:58', 9:58:26), format = '%H:%M:%S')
Then you will have a time object, i.e: times[2] - times[1] will give you: Time diff of -32 secs.
You can plot these as is, also they can be formatted by using format(x, format).
Ex: format(times[1], format = '%H:%M:%S') will give you '09:58:58'.
Related
I have a "Time" column in R with a set of character time values in HH:MM:SS
However, some of the times do not have the seconds, which makes conversion from char to chron() impossible
Example:
library(chron)
x <- c("08:25:18","08:25","08:24:57","08:24:47")
I want to convert x to chron(), but without the seconds it converts that value to N/A
How can I add :00 seconds to just those that need it? Thanks
We could convert to date time, format it and then apply the times
library(chron)
library(lubridate)
out1 <- times(format(parse_date_time(x, c('HMS', 'HM')), "%H:%M:%S"))
str(out1)
#'times' num [1:4] 08:25:18 08:25:00 08:24:57 08:24:47
# - attr(*, "format")= chr "h:m:s"
Or specify the times in chron
chron(times = format(parse_date_time(x, c('HMS', 'HM')), "%H:%M:%S"))
Or use as.ITime from data.table which would work
library(data.table)
as.ITime(x)
#[1] "08:25:18" "08:25:00" "08:24:57" "08:24:47"
Is there a way to convert a string of characters to a time that retains the fractional seconds, but does not add a date to the data?
Background: Data that I saved overnight (starting at 22:00 and ending at 06:00) is recorded with a time, but not a date.
I would like to be able to perform something like an "if" statement on the times (i.e. if (time < midnight) date = yesterday.... else date = today)
I don't want to use something like strptime, because strptime adds today's date to the data:
> options(digits.secs=3)
> strptime("22:59:54.807", format="%H:%M:%OS")
[1] "2019-01-20 22:59:54.807 AEDT"
When I use times from the chron package, the fractional seconds are dropped:
> options(digits.secs=3)
> times("22:59:54.807")
[1] 22:59:55
Using base::strftime(), you can obtain a character of the desired time to any divide of seconds you want. Below I have saved the current time to unit 1/1000 of a second, using the number "4" after "OS":
Using current system time:
time = Sys.time()
str(time)
POSIXct[1:1], format: "2019-01-19 15:41:28.185"
newTime = strftime(Sys.time(), format="%H:%M:%OS4")
str(newTime)
chr "15:41:28.1851"
newTime
[1] "15:41:28.1851"
Want to change the class for Time to POSIXlt and extract only the hours minutes and seconds
str(df3$Time)
chr [1:2075259] "17:24:00" "17:25:00" "17:26:00" "17:27:00" ...
Used the strptime function
df33$Time <- strptime(df3$Time, format = "%H:%M:%S")
This gives the date/time appended
> 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" ...
Wanted to extract just the time without changing the POSIXlt class. using the strftime function
df3$Time <- strftime(df3$Time, format = "%H:%M:%S")
but this converts the class back to "char" -
> class(df3$Time)
[1] "character"
How can I just extract the time with class set to POSIX or numeric...
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.
A "modern" tidyverse answer to this is to use hms::as_hms()
For example
library(tidyverse)
library(hms)
as_hms(1)
#> 00:00:01
as_hms("12:34:56")
#> 12:34:56
or, with your example data:
x <- as.POSIXlt(c("17:24:00", "17:25:00", "17:26:00", "17:27:00"), format = "%H:%M:%S")
x
#>[1] "2021-04-10 17:24:00 EDT" "2021-04-10 17:25:00 EDT" "2021-04-10 17:26:00 EDT" "2021-04-10 17:27:00 EDT"
as_hms(x)
# 17:24:00
# 17:25:00
# 17:26:00
# 17:27:00
See also docs here:
https://hms.tidyverse.org/reference/hms.html
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
I have a column named timings of class factor with time stamps in the following format:
1/11/07 15:15
I applied strptime on timings to generate tStamp as follows:
tStamp=strptime(timings,format="%m/%d/%Y %H:%M")
i)
The corresponding entry in tStamp looks like 0007-01-11 15:15:00 now. Why has it made 2007 or 07 into 0007? What is a correct way to generate tStamp?
ii)
After generating tStamp correctly, how do we convert it to the Unix time Seconds. (Seconds since...1970) format?
You need the lowercase %y for 2-digit years:
R> pt <- strptime("1/11/07 15:15",format="%m/%d/%y %H:%M")
R> pt
[1] "2007-01-11 15:15:00 CST"
R>
where CST is my local timezone.
And as.numeric() or as.double() converts to a double ...
R> as.numeric(pt)
[1] 1168550100
... which has fractional seconds if those are in the input:
R> options("digits.secs"=3) # show milliseconds
R> as.numeric(Sys.time()) # convert current time
[1] 1372201674.52 # now with sub0seconds.
How can I add one hour to all the elements of the index of a zoo series?
I've tried
newseries <- myzooseries
index(newseries) <- index(myzooseries)+times("1:00:00")
but I get the message
Incompatible methods ("Ops.dates", "Ops.times") for "+"
thanks
My index is a chron object with date and time but I've tried with simpler examples and I can't get it
This is easily solved by adding the time you want in a numerical fashion :
newseries <- myzooseries
index(newseries) <- index(myzooseries) + 1/24
chron objects are represented as decimal numbers, so you can use that to calculate. A day is 1, so an hour is 1/24, a minute 1/1440 and so on. You can see this easily if you use the function times. This gives you the times of the object tested, eg :
> A <- chron(c("01/01/97","01/02/97","01/03/97"))
> B <- A + 1/24
> B
[1] (01/01/97 01:00:00) (01/02/97 01:00:00) (01/03/97 01:00:00)
> times(A)
Time in days:
[1] 9862 9863 9864
> times(B)
Time in days:
[1] 9862.042 9863.042 9864.042
> times(B-A)
[1] 01:00:00 01:00:00 01:00:00
> times(A[3]-B[1])
Time in days:
[1] 1.958333
Convert to POSIXct, add 60*60 (1h in s) and then convert back.