load data from xlsx file as date and time - r

Now a xlsx file contained a date column as :
Date
2019-3-1 0:15
2019-3-1 19:15
2019-3-1 23:15
How can I load it into data.frame as read date and time datatype? My tool is openxlsx package and I tried like:
df <- readWorkbook(xlsxFile = '0301-0314.xlsx',sheet=1)

First you read the data set using any library. Then you can try as.POSIXlt or as.POSIXct to define the date-time format. This also allows you to provide timezone info along with date-time format.
Example:
> sampledf <- data.frame(DateTime = c("2019-3-1 0:15",
+ "2019-3-1 19:15",
+ "2019-3-1 23:15")
+ )
> str(sampledf$DateTime)
Factor w/ 3 levels "2019-3-1 0:15",..: 1 2 3
> sampledf$DateTime <- as.POSIXlt(sampledf$DateTime ,"GMT",format = "%Y-%m-%d %H:%M")
> str(sampledf$DateTime)
POSIXlt[1:3], format: "2019-03-01 00:15:00" "2019-03-01 19:15:00" ...
Timezone info "GMT" can be replace with any time zone.
More about different time formatting options in R is available here.

This will work:
# Create example dataset:
df <- data.frame(Date = c("2019-3-1 0:15",
"2019-3-1 19:15",
"2019-3-1 23:15")
)
df$Date <- as.character(df$Date)
# Format "Date" as date and time:
df$time <- strptime(as.character(df$Date), "%Y-%m-%d %H:%M")
# Check:
str(df)
# If then you would like to count time, for example in number of hours, from a certain initial time (e.g. 2019-3-1 0:15) try:
df$timestep <- as.numeric(difftime(time2="2019-3-1 0:15", time1=df$time, units="hours"))

Related

Can anyone help me to change factor to date in r?

I imported a csv file with dates to R. The dataframe is named DT, and one of the column called date has year and month in it.
class(DT$date)
[1] "factor"
head(DT$date)
[1] 2013年1月 2013年1月 2013年1月 2013年1月 2013年1月 2013年1月
60 Levels: 2013年10月 2013年11月 2013年12月 2013年1月 ... 2017年9月
And I tried to use as.Date to convert it to date format:
date <- as.Date(DT$date, format = "%Y/%m")
date <- as.Date(as.factor(DT$date), format = "%Y/%m")
date <- as.Date(as.factor(DT$date), format = "%Y/%m/%d")
During this operation I lose all my dates. Then I tried the lubridate package:
date <- ymd(DT$date)
date <- as.yearmon( DT$date)
However, I lose all my dates again. Can anyone help me to change this factor to Date in R?
Thanks.
The following seems to work:
DT = data.frame(date = c("2013年1月", "2013年11月", "2017年9月"))
lubridate::parse_date_time(DT$date, orders = "ym")
You should generally start with the parse_date_time function.

parsing a character date time format in R

I am trying to parse a column into two variables, "date" and "time" in R. I have installed the lubridate library.
The current csv file has the following timestamp format: yyyyMMdd hh:mm a (e.g. '20170423 12:26 AM') and imports the column as character.
I'm trying this but its not working on my current variable 'Tran_Date' (below code doesn't work):
transactions_file <- as_date('Tran_Date', "%Y%m%d %H:%M %p")
I like the base R solution like this,
Tran_Date <- as.POSIXct("20170423 12:26 AM", format = "%Y%m%d %I:%M %p")
Tran_Date
#> [1] "2017-04-23 00:26:00 CEST"
transactions_file <- data.frame(
date = format(Tran_Date,"%m/%d/%Y"),
time = format(Tran_Date,"%H:%M")) # possibly add %p if you use %I
transactions_file
#> date time
#> 1 04/23/2017 00:26
with lubridate,
# install.packages(c("tidyverse"), dependencies = TRUE)
library(lubridate)
Tran_Date <- ymd_hm("20170423 12:26 AM")
then you could recycle the above or use some combination of day(Tran_Date) cbind paste with month(Tran_Date) and similar with paste(hour(Tran_Date), minute(Tran_Date), sep = ":") or most likely something smarter.

How to change date format from YYYY/MM/DD to DD/MM/YYYY

I have a column of dates which were read in as character values (yes, they are supposed to be the same):
str(df$date)
$ date : chr "30/08/2017" "30/08/2017" "30/08/2017" "30/08/2017"
I then convert the values to Date format:
str(df$date)
$ date : Date, format: "2017-08-30" "2017-08-30" "2017-08-30"
The problem is that no matter which method I choose to use, the resulting dates are always in YYYY/MM/DD format, which is not what I want; they should be in DD/MM/YYYY format.
I try:
df$date <- as.Date(df$date, format = "%d/%m/%Y")
df$date <- strptime(df$date, format = "%d/%m/%Y")
df$date <- as.POSIXct(df$date, format = "%d/%m/%Y")
and they all produce the same format.
I have read numerous similar Stack Overflow posts as well as some guides and have tried things like getting and setting my system locale (United Kingdom) and all is correct in that respect.
Where am I going wrong?
I try:
df$date <- as.Date(df$date, format = "%d/%m/%Y")
df$date <- strptime(df$date, format = "%d/%m/%Y")
df$date <- as.POSIXct(df$date, format = "%d/%m/%Y")
and they all produce the same format.
R has two very similarly named functions: strptime, which converts from character strings to Date data, and strftime, which converts Dates to formatted strings. To make matters worse, the documentation for these two functions is combined, so it can be very hard to keep their uses straight. You want strftime, in this case.
You can also use format:
date = c("30/08/2017", "30/08/2017", "30/08/2017", "30/08/2017")
date <- as.Date(date, format = "%d/%m/%Y")
# > date
# [1] "2017-08-30" "2017-08-30" "2017-08-30" "2017-08-30"
date = format(date, "%m/%d/%Y")
# > date
# [1] "08/30/2017" "08/30/2017" "08/30/2017" "08/30/2017"
Turns into character class:
# > class(date)
# [1] "character"
This will help you:
$variable = '2018/09/18';
$date = str_replace('/', '/', $variable);
echo date('d/m/Y', strtotime($date));
Please check and let me know if you need any more help.

How to convert dates in a dataframe to a Date datatype?

I've imported one date value into R:
dtime <- read.csv("dtime.csv", header=TRUE)
It's output (7th Nov, 2013) is printed as:
> dtime
Date
1 07-11-2013 23:06
and also its class is 'factor'.
> class(dtime$Date)
[1] "factor"
Now, I want to extract the time details (hours, minutes, seconds) from the data. So, I was trying to convert the dataframe's date value to Date type. But none of the following commands worked:
dtime <- as.Date(as.character(dtime),format="%d%m%Y")
unclass(as.POSIXct(dtime))
as.POSIXct(dtime$Date, format = "%d-%m-%Y %H:%M:%S")
How do I achieve this in R???
Your attempts didn't work because the format specified was wrong.
With base R there are two possible ways of solving this, with as.POSIXlt
Res <- as.POSIXlt(dtime$Date, format = "%d-%m-%Y %H:%M")
Res$hour
Res$min
Also, for more options, see
attr(Res, "names")
## [1] "sec" "min" "hour" "mday" "mon" "year" "wday" "yday" "isdst" "zone" "gmtoff"
Or a bit less conveniently with as.POSIXct
Res2 <- as.POSIXct(dtime$Date, format = "%d-%m-%Y %H:%M")
format(Res2, "%H") # returns a character vector
format(Res2, "%M") # returns a character vector
I would like to contribute solution utilising lubridate :
dates <- c("07-11-2013 23:06", "08-10-2012 11:11")
dta <- data.frame(dates)
require(lubridate)
dta$properDate <- dmy_hm(dta$dates)
If needed, lubridate will enable you to conveniently specify time zones or extract additional information.

how to convert factor into DateTime in R?

This question might be simple for some of you but bear with me since I'm a beginner in R.
I have a dataframe that has a factor column (called time) containing DateTime data as the following:
time
01/01/2011 00:10
02/01/2011 03:00
03/01/2011 05:00
04/01/2011 10:03
I want to convert this column into DateTime column in R. I searched and tried some functions but it gives me 'NA' results. The following functions are those I tried:
> dataframe1$datetime <- as.POSIXlt(as.character(dataframe1$time), format="%d/%m/%Y %H:%M")
> dataframe1$datetime <- as.POSIXlt(strptime(dataframe1$time), format="%d/%m/%Y %H:%M")
> dataframe1$datetime <- as.POSIXlt(dataframe1$time, format="%d/%m/%Y %H:%M")
> dataframe1$datetime <- as.chron(dataframe1$time, "%d/%m/%Y %H:%M")
I don't know what else to try. I want ideally to add three columns namely datetime, date, and time.
Try:
dataframe1$datetime <- strptime(x = as.character(dataframe1$datetime),
format = "%d/%m/%Y %H:%M")
Probably the easiest thing to do is use the lubridate packages which has a large number of functions for date manipulation. The following will convert your time into a POSIXct object:
library(lubridate)
mdy_hm( as.character(dataframe1$time) )
See ?mdy to see the variety of date parsing functions.
For a slightly more verbose version that does not rely on lubridate
strptime(x = as.character( dataframe1$datetime ), format = "%d/%m/%Y %H:%M")

Resources