R convert character "111213" into time "11:12:13".
strptime("111213", format="%H%m%s") gives NA
and
strptime("111213", "%H%m%s") gives 1970-01-01 01:00:13 CET
I think the canonical answer would be as in my comment:
format(strptime("111213", format="%H%M%S"), "%H:%M:%S")
#[1] "11:12:13"
where you can read ?strptime for all the details. format is a generic function, and in this specific case we are using format.POSIXlt.
Another solution is to merely play with string:
paste(substring("111213", c(1,3,5), c(2,4,6)), collapse = ":")
#[1] "11:12:13"
This makes sense because your input is really not a Date-Time: there is no Date.
We can use
library(chron)
times(gsub("(.{2})(?=\\d)", "\\1:", "111213", perl = TRUE))
#[1] 11:12:13
To manipulate time, you can use hms package.
By default, it working with %H:%M;%S (or %X format).
For you specifique time format ("111213"), you need to go through base function as.difftime
hms::as.hms(as.difftime("111213", format = "%H%M%S"))
#> 11:12:13
So if we incorporate also date in similar "integer" format we can obtain command :
strptime("20181017 112233", format="%Y%m%d %H%M%S")
Related
I want to convert strings such as "19-SEP-2022" to date. Is there any available function in R? Thank you.
Just to complete I want to add parse_date_time function from lubridate package. With no doubt, the preferred answer here is that of #Marco Sandri:
library(lubridate)
x <- "19-SEP-2022"
x <- parse_date_time(x, "dmy")
class(x)
[1] "2022-09-19 UTC"
> class(x)
[1] "POSIXct" "POSIXt"
Yes, strptime can be used to parse strings into dates.
You could do something like strptime("19-SEP-2022", "%d-%b-%Y").
If your days are not zero-padded, then use %e instead of %d.
A decade or so ago I starting writing the anytime package because of the firm belief that for obvious date(time) patterns we should not need to specify patterns, or learn grammars.
I still use it daily, and so do a bunch of other CRAN users.
> anytime::anydate("19-SEP-2022")
[1] "2022-09-19"
>
So here we do exaxtly what you ask for: supply the string, return a date object.
For example i have a string that contains time characters like this
Time<-c("1:00","15:09","1:06","23:13")
I want to turn them into h:m:s
Time<-c("01:00:00","15:09:00","01:06:00","23:13:00")
Is there a way to do this so I add the zero's in the proper place and also note the original does not have seconds so seconds will be read as zeros.
The as.ITime from data.table does add the seconds
library(data.table)
as.ITime(Time)
#[1] "01:00:00" "15:09:00" "01:06:00" "23:13:00"
Or in base R with as.POSIXct and format
format(as.POSIXct(Time, format = '%H:%M'), '%H:%M:%S')
#[1] "01:00:00" "15:09:00" "01:06:00" "23:13:00"
I have data which have the format of YYYYMM and I wish convert it to YYYY-MM format.
exemple : 201805 should be in the format of 2018-05
How could I do it please ?
We can use as.yearmon from zoo to convert it to yearmon object and then do the format
library(zoo)
format(as.yearmon(as.character(v1), "%Y%m"), "%Y-%m")
#[1] "2018-05"
data
v1 <- 201805
I like the idea of using actual dates here. If the days component does not matter to you, then you may arbitrarily just set each of your dates to the first of the month. Then, we can leverage R's dates functions to handle the heavy lifting.
x <- "201805"
x <- paste0(x, "01")
x
y <- format(as.Date(x, format = "%Y%m%d"), "%Y-%m-%d")
substr(y, 1, 7)
[1] "20180501"
[1] "2018-05"
You could use regular expressions:
data <- "201805"
sub("(\\d{4})", "\\1-", data)
[1] "2018-05"
Another variant, using only lookarounds:
sub("(?<=\\d{4})(?=\\d{2})", "-", data, perl=TRUE)
How about following one(I am considering that OP need not to perform any checks on its variable's value here).
val="201805"
sub("(..$)","-\\1",val)
OR to perform substitution with last 2 digits only try following.
val="201805"
sub("(\\d{2}$)","-\\1",val)
[1] "2018-05"
Very similar to some of the others, but because I find the package useful I will mention it:
library(lubridate)
date <- "201805"
format(ymd(paste0(date,"01")), "%Y-%m")
Lubridate can make life easy if the formats start to vary.
Here is another option albeit a longer one:
library(tidyverse)
somestring<-"201805"
stringi::stri_sub(somestring,1,4)<-"-"
somestring1<-"201805"
somestring2<-substring(somestring1,1,4)
as.character.Date(paste0(somestring2,somestring))
Result:
"2018-05"
I'm simply attempting to take a string (char) time (mm:ss.s) (minute:second.fractional second) to a POSIXct object.
I've attempted many solutions with base R and lubridate, but I can't seem to preserve the fractional second.
In Python, I can simply use to_datetime and I can parse out what I need into the correct object type.
I'm wondering from the community if there is a solution.
The column data looks like this if you need a more clear visual:
> glimpse(update_times$Times)
chr [1:318] "24:45.0" "24:11.8" "22:22.6"
Thank you in advance. Much appreciated!
lubridate::ms(c("24:45.0", "24:11.8", "22:22.6"))
## [1] "24M 45S" "24M 11.8S" "22M 22.6S"
I believe this is possible with the standard strptime() function. From help(strptime):
## time with fractional seconds
z <- strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
z # prints without fractional seconds
op <- options(digits.secs = 3)
z
options(op)
I'm using strptime to extract date and the result is a wrong year
Where is the error in the below code:
strptime('8/29/2013 14:13', "%m/%d/%y")
[1] "2020-08-29 PDT"
What are the other ways to extract date and time as separate columns.
The data I have is in this format - 8/29/2013 14:13
I want to split this into two columns, one is 8/29/2013 and the other is 14:13.
You have a four digit year so you need to use %Y
strptime('8/29/2013 14:13', "%m/%d/%Y" )
[1] "2013-08-29 CEST"
Do you really want data and time in separate columns? It usually much easier to deal with a single date-time object.
Here's one possibility to separate time and date from the string.
For convenience, we could first convert the string into a POSIX object:
datetime <- '8/29/2013 14:13'
datetime.P <- as.POSIXct(datetime, format='%m/%d/%Y %H:%M')
Then we can use as.Date() to extract the date from this object and use format() to display it in the desired format:
format(as.Date(datetime.P),"%m/%d/%Y")
#[1] "08/29/2013"
To store the time separately we can use, e.g., the strftime() function:
strftime(datetime.P, '%H:%M')
#[1] "14:13"
The last function (strftime()) is not vectorized, which means that if we are dealing with a vector datetime containing several character strings with date and time in the format as described in the OP, it should be wrapped into a loop like sapply() to extract the time from each string.
Example
datetime <- c('8/29/2013 14:13', '9/15/2014 12:03')
datetime.P <- as.POSIXct(datetime, format='%m/%d/%Y %H:%M')
format(as.Date(datetime.P),"%m/%d/%Y")
#[1] "08/29/2013" "09/15/2014"
sapply(datetime.P, strftime, '%H:%M')
#[1] "14:13" "12:03"
Hope this helps.