at the moment I'm trying to convert a string into time-format.
e.g. my string looks like following: time <- '12:00'.
I already tried to use the chron-Package. And my code looks like following:
time <- paste(time,':00', sep = '') time <- times(time)
Instead of getting a value like "12:00:00" the function times() always translate the object time into "0.5"
Am I using the wrong approach?
regards
Your code works. If you check the 'class()' it is "times". However, if you want another way, try:
time <- '12:00:00'
newtime<-as.POSIXlt(time, format = "%H:%M:%S") # The whole date with time
t <- strftime(newtime, format="%H:%M:%S") # To extract the time part
t
#[1] "12:00:00"
Cheers !
Related
I have a problem with the as.date function.
I have a list of normal date shows in the excel, but when I import it in R, it becomes numbers, like 33584. I understand that it counts since a specific day. I want to set up my date in the form of "dd-mm-yy".
The original data is:
how the "date" variable looks like in r
I've tried:
as.date <- function(x, origin = getOption(date.origin)){
origin <- ifelse(is.null(origin), "1900-01-01", origin)
as.Date(date, origin)
}
and also simply
as.Date(43324, origin = "1900-01-01")
but none of them works. it shows the error: do not know how to convert '.' to class “Date”
Thank you guys!
The janitor package has a pair of functions designed to deal with reading Excel dates in R. See the following links for usage examples:
https://www.rdocumentation.org/packages/janitor/versions/2.0.1/topics/excel_numeric_to_date
https://www.rdocumentation.org/packages/janitor/versions/2.0.1/topics/convert_to_date
janitor::excel_numeric_to_date(43324)
[1] "2018-08-12"
I've come across excel sheets read in with readxl::read_xls() that read date columns in as strings like "43488" (especially when there is a cell somewhere else that has a non-date value). I use
xldate<- function(x) {
xn <- as.numeric(x)
x <- as.Date(xn, origin="1899-12-30")
}
d <- data.frame(date=c("43488"))
d$actual_date <- xldate(d$date)
print(d$actual_date)
# [1] "2019-01-23"
Dates are notoriously annoying. I would highly recommend the lubridate package for dealing with them. https://lubridate.tidyverse.org/
Use as_date() from lubridate to read numeric dates if you need to.
You can use format() to put it in dd-mm-yy.
library(lubridate)
date_vector <- as_date(c(33584, 33585), origin = lubridate::origin)
formatted_date_vector <- format(date_vector, "%d-%m-%y")
How can I convert dates in R to a string without dashes or slashes or letters and times without colons. For example I can get 2017-12-07 in R but I need 201712071520 to use in an Weather API call. How can I do that? For reference please see the example call below for startDateTime and endDateTime. I would like to convert the dates that I have into 20171207 format and append it with a fixed time (1520) without the colon. Thanks for helping!
I have been told this question has been asked before but the other examples are doing the opposite converting character strings into R dates and times.
Here is an example of the API I am calling:
https://api.weather.com/v3/wx/hod/conditions/historical/point?pointType=nearest&geocode=39.86,-104.67&startDateTime=201712071520&endDateTime=201712071520&units=e&format=json&apiKey=yourApiKey
Moved from comments.
If x is of R's "Date" class then use the indicated format statement:
x <- as.Date("2017-12-07") # test input
format(x, "%Y%m%d1520")
## [1] "201712071520"
See ?strptime for more on percent codes.
This is a bit more generic solution. It would look like this:
library(lubridate)
input_date = "2017-1-7" #intentionally taking different date to make it more generic
fixed_text = "1520"
input_date = ymd(input_date)
output_date = paste(year(input_date), sprintf(fmt = '%02d', month(input_date)), sprintf(fmt = '%02d', day(input_date)), fixed_text, sep = "")
print(output_date)
I have been trying to use the as.PosIXct() to import a combined date & time variable from Excel to R. The format that I want to import looks like this: '2016-09-25 17:13:46.030'. I want it to look like this in R: '2016-09-25 17:13:46'. When I use the code below, I get back only NA values.
fd$AnswerValue <- as.POSIXct(as.character(fd$AnswerValue),
format = '%y%m%d%H%M', origin = '2011-07-15 13:00:00')
I expect this has something to do with the three additional decimals of the second counts in the original file. Anyone with advice?
A lubridate solution would be:
test <- "2016-09-25 17:13:46.030"
library(lubridate)
ymd_hms(test)
Or the base function, but longer:
as.POSIXct(as.character(test),
format = '%Y-%m-%d %H:%M:%S', origin = '2011-07-15 13:00:00')
I am working with data from csv files that will all look the same so I am hoping to come up with a code that can be easily applied to all of them.
However, sadly enough I am failing at step one :-(.
The csv files have the date and time saved in one column, so when I import them with read.csv that column gets read as a chr. How can I most easily convert this into a date that I then can use for plotting and analysis?
Here is what I tried:
load the data --> will save the date and time as chr under mydata$Date.Time (e.g. 1/1/15 0:00)
mydata<-read.csv(file.choose(), stringsAsFactors = FALSE,
strip.white = TRUE,
na.strings = c("NA",""), skip=16,
header=TRUE)
separate the Date.Time into Date and Time:
new <- do.call( rbind , strsplit( as.character( mydata$Date.Time ) , " " ) )
add these two back to the df mydata:
cbind( mydata , Date = new[,2] , Time = new[,1] )
convert Date into a date format via as.Date:
mydata$Date <- as.Date(new[,1], format="")
So this works fine for the date however I am stuck with the time, I tried this:
mydata$Time <- format(as.POSIXct(new[,2], format="%H:%M"))
this gives me the following error:
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format
I wonder if there is a smarter way of doing this? Reading in time and date seems to be one of the substantial tasks that I would like to understand. Is there a way of R directly recognizing the date and time from the csv? Or is it generally smarter to generate a time vector by its own, if so how would I do that?
Thanks so much for your help.
Sandra
If you want to use time only, consider using the chron package:
library(chron)
mytime <- times("21:19:37")
or in your case
times(new[,2])
assuming that that's a character vector.
I tried the chron approach but it wouldn't work for me :-(.
So what I ended up doing is just creating a time vector for the period that I am loading the data in for:
date <-seq(as.POSIXct("2015/1/1 00:00"), as.POSIXct("2015/1/31 23:00"), "hours")
and then adding it back to the df.
Not what I wanted but it will work until I find the ultimate solution :-)
I am wanting to convert date-times stored as characters to date-time objects.
However if a date time includes midnight then the resulting datetime object excludes the time component, which then throws an error when used in a later function (not needed here - but a function that extracts weather data for specified location and date-time).
Example code:
example.dates <- c("2011-11-02 00:31:00","2011-11-02 00:00:00","2011-11-02 00:20:22")
posix.dates <- as.POSIXct(example.dates, tz="GMT", format="%Y-%m-%d %H:%M:%S")
posix.dates
posix.dates[2]
NB times is only excluded when the datetime containing midnight is called on it's own (atomic vector).
Is there a way of retaining the time data for midnight times? Can you suggest an alternative function?
Okay, after some time I can reconfirm your problem.
For me this looks like a bug in R. I would suggest you to report it on https://bugs.r-project.org/bugzilla3/.
As a temporary workaround, you could try if it helps to overwrite the strptime function like this:
strptime <- function (x, format, tz = "")
{
if ("POSIXct" %in% class(x)) {
x
} else {
y <- .Internal(strptime(as.character(x), format, tz))
names(y$year) <- names(x)
y
}
}
Realise this is an old question now, but I had the same issue and found this solution:
https://stackoverflow.com/a/51195062/8158951
Essentially, all you need to do is apply formatting as follows. The OP's code needed to include the formatting call after the POSIXct function call.
posix.dates <- format(as.POSIXct(example.dates, tz="GMT"), format="%Y-%m-%d %H:%M:%S")
This worked for me.
I prefer to use the lubridate package for date-times. It does not seem to cause problems here either:
example.dates <- c("2011-11-02 00:31:00","2011-11-02 00:00:00","2011-11-02 00:20:22")
library(lubridate)
ymd_hms(example.dates)