Extract Time and date from POSIXct - r

I have a vector with DateTime character ("2014-04-17 23:33:00") and want to make a matrix with date and time as my columns.
This is my code:
dat <- as.POSIXct(dates)
date = data.frame(
date=dat,
time=format(dat, "%H:%M")
)
I took a look at extract hours and seconds from POSIXct for plotting purposes in R and it helped, but the problem is that I only get 00:00 as the time in my time column. It does not extract the time from the dates vector.
Any help is appreciated.

Using the following vector as an example:
dates<- c("2012-02-06 15:47:00","2012-02-06 15:02:00")
dat <- as.POSIXct(dates)
date.df = data.frame(
date=dat,
time=format(dat, "%H:%M")
)
You will obtain the correct times ("%H:%M")
> date.df
date time
1 2012-02-06 15:47:00 15:47
2 2012-02-06 15:02:00 15:02

Related

What's the best way to aggregate date time by hourly interval?

I'm having trouble parsing my date time column that are currently in 'chr' type. I want the date time to be grouped by hour interval and sum corresponding values, then merge two date frames.
a <- c("2016-04-12 12:00:00", "2016-04-12 12:01:00")
b <- c(10, 20)
df_1 <- data.frame(a,b)
names(df_1) <- c('Date', 'Steps')
c1 <- c("4/12/2016 12:00:00 AM", "4/12/2016 05:00:00 PM")
d <- c(20,8)
df_2 <- data.frame(c1,d)
names(df_2) <- c('Date', 'Intensity')
df_1 (with minutes interval) to join df_2 (with hourly interval but the whole day is separated by AM PM)
I have tried converting it using as.POSIXct and ymd to datetime type but it's returning NA values. I tried below code from a post I saw before, it worked but it didn't record the PM time of the day. code below
df_1 <- aggregate(df_1["Steps"],
list(Date=cut(as.POSIXct(df_1$Date), "hour")),
sum)
Also, I wanna remove that AM PM on the second date frame.
While the aggregate for df_1 appears to work fine, for df_2 you need to define the time format, using strptime which converts character objects to "POSIX*t".
aggregate(df_2["Intensity"],
list(Date=cut(strptime(df_2$Date, '%m/%d/%Y %I:%M:%S %p'), "hour")),
sum)
# Date Intensity
# 1 2016-04-12 05:00:00 8
# 2 2016-04-12 12:00:00 20
Explanation:
%m/%d/%Y month, day, year, separated by a slash
the space between date and time
%I:%M:%S hour (12h format), minute, second, separated by a colon
another space
%p the AM/PM indicator
Read ?strptime for different options, since this may also depend on your locale.

Convert date time in R to date time for time series

I have this dataframe where DT is in char, i would like to convert it into date time format in R so that i can plot a time series
DT Name
12-12-21 1:30 James
01-01-22 12:30 Job
03-02-22 1:00 Seth
03-02-22 1:14 Michael
I explored the following code
time <- as.POSIXct(dataframe$DT, format="%m-%d-%Y %H:%M")
but it returned year as 01-01-0021 instead of 01-01-2021, may i know how could i specify the year so that it could be read as 2021?
Instead of %Y, use %y. :
time <- as.POSIXct(dataframe$DT, format="%m-%d-%y %H:%M")
A possible solution
time<-as.POSIXct(dataframe$DT,format="%m/%d/%y %H:%M")
or
# install.packages("hms")
library(hms)
time <- as.hms(dataframe$DT)

Can I specify the dates and times of a time series in R?

I have a dataset that contains times and dates in the first column, and the stock prices in the second column.
I used the following format.
Time Price
2015-02-01 10:00 50
I want to turn this into a time series object. I tried ts(data) function, but when I plot the data I cannot observe the dates in the x-axis. Also I tried ts(data, start=) function. Because I have some hours with missing prices, and those hours are not included in my data set, if I set start date and frequency, my plot will be misleading.
Here is the sample data that I have. It is called df.
time price
1 2013-05-01 00:00:00 124.30
2 2013-05-01 01:00:00 98.99
3 2013-05-01 02:00:00 64.00
4 2013-05-01 03:00:00 64.00
This is the code that I used
Time1 <- ts(df)
autoplot(Time1)
Also tried this,
Time1 <- zoo(Time_series_data[,2], order.by = Time_series_data[,1])
Time_n <- ts(Time1)
autoplot(Time1)
However, when I plot the graph with autoplot(Time1) the x-axis doesn't show the times that I specified but numbers from 0 to 4. I want to have plot of a ts object that includes the date columns in the x-axis and values in Y
Is there any way to convert it to a time series object in R. Thanks.
Try the following:
Create some data using the nifty tribble function from the tibble package.
library(tibble)
df <- tribble(~time, ~price,
"2013-05-01 00:00:00", 124.30,
"2013-05-01 01:00:00", 98.99,
"2013-05-01 02:00:00", 64.00,
"2013-05-01 03:00:00", 64.00)
The time column is a character class and cannot be plotted in the usual way. So convert it using as.Posixct. I'll use the dplyr package here but that's optional.
library(dplyr)
df <- df %>%
mutate(time=as.POSIXct(time))
Next, convert the data to a time series object. This requires the xts package, although I'm sure there are other options including zoo.
library(xts)
df.ts <- xts(df[, -1], order.by=df$time)
Now you can visualise the data.
plot(df.ts) # This should call the `plot.xts` method
And if you prefer ggplot2.
library(ggplot2)
autoplot(df.ts)

How to convert Hour Minutes character format into a POSIXlt format?

Current situation:
mydate <- "14:45"
class(mydate)
The current class of this value is a character. I would like to convert it into a POSIXlt format.
I tried the strptime() function but it unfortunately adds the full date to my hours when I actually only need Hours:Minutes
mydate <- strptime(mydate, format = "%H:%M")
What can I do to get a POSIXlt format uniquely containing hours and minutes ?
Thanks in advance for your returns !
POSIXlt and POSIXct always contain date and time. You can use chron times class to represent times less than 24:00:00.
library(chron)
tt <- times(paste(mydate, "00", sep = ":"))
tt
## [1] 14:45:00
times class objects are represented internally as a fraction of a day so, for example, adding 1/24 will add an hour.
tt + 1/24 # add one hour
## [1] 15:45:00
For me it works like this:
test <- "2016-04-10T12:21:25.4278624"
z <- as.POSIXct(test,format="%Y-%m-%dT%H:%M:%OS")
#output:
z
"2016-04-10 12:21:25 CEST"
The code is form here: R: convert date from character to datetime

How to conduct timeseries analysis on half-hourly data?

I have the dataset below with half hourly timeseries data.
Date <- c("2018-01-01 08:00:00", "2018-01-01 08:30:00",
"2018-01-01 08:59:59","2018-01-01 09:29:59")
Volume <- c(195, 188, 345, 123)
Dataset <- data.frame(Date, Volume)
I would like to know how to read this dataframe in order to conduct time series analysis. How should I define starting and ending date and what the frequency will be?
I'm not sure what you exactly mean by "half hour data" since it isn't. In case you want to round it to half hours, we can adapt this solution to your case.
Dataset$Date <- as.POSIXlt(round(as.double(Dataset$Date)/(30*60))*(30*60),
origin=(as.POSIXlt('1970-01-01')))
In case you don't want to round it just do
Dataset$Date <- as.POSIXct(Dataset$Date)
Basically your Date column should be formatted to a date format, e.g. "POSIXlt" so that e.g.:
> class(Dataset$Date)
[1] "POSIXlt" "POSIXt"
Then we can convert the data into time series with xts.
library(xts)
Dataset.xts <- xts(Dataset$Volume, order.by=Dataset$Date)
Result (rounded case):
> Dataset.xts
[,1]
2018-01-01 08:00:00 195
2018-01-01 08:30:00 188
2018-01-01 09:00:00 345
2018-01-01 09:30:00 123
you can use dplyr and lubridate from tidyverse to get the data into a POSIX date format, then convert to time series with ts. Within that you can define parameters.
Dataset2 <- Dataset %>%
mutate(Date = as.character(Date),
Date = ymd_hms(Date)) %>%
ts(start = c(2018, 1), end = c(2018, 2), frequency = 1)
try ?ts for more details on the parameters. Personally I think zoo and xts provide a better framework for time series analysis.

Resources