I was trying this piece of code in R about data-time formats in one of the online courses. It gives me the required output but I am unable to figure out how it works, especially the referencing a function name with the same function.
str2 <- "2012-3-12 14:23:08"
# Convert the strings to POSIXct objects: time2
time2 = as.POSIXct(str2, format = "%Y-%m-%d %H:%M:%S")
# Convert times to formatted strings: Confusion over this piece of code format within format
format(time2, format="%H hours: %M minutes %p")
The output is "14 hours: 23 minutes PM", which is fine. But, I am unable to figure out the syntax of how format within format works. Can anyone please help?
format is a generic function. The correct method will be called based on the class of the object passed as the first argent. For POSIXct objects the method format.POSIXct will be called.
?format.POSIXct shows it accepts the format argument.
Related
Hi and thanks for reading me. Im trying to convert a character string in to a datetime format in r, but I cannot discover the way to do that, because the year is only taken the last 2 digits ("22" instead of "2022"), im not sure of how to fix It.
The character string is "23/8/22 12:45" and I tried with:
as.Date("23/8/22 12:45", format ="%m/%d/%Y" )
and
as_datetime(ymd_hm("23/8/22 12:45"), format ="%m/%d/%Y")
But it doest work. Anyone knows how I can fix it? thanks for the help
as.Date returns only the calendar date, because class Date objects are only shown as calendar dates.
in addition to POSIXct, you can also use parse_date_time from lubridate package:
library(lubridate)
parse_date_time("23/8/22 12:45", "dmy HM", tz="") #dmy - day, month, year HM - hour, minute
# Or the second function:
dmy_hm("23/8/22 12:45",tz=Sys.timezone())
As has been mentioned in the comments you need to use "%d/%m/%y" to correctly parse the date in your string. But, if you want datetime format (in base r this is normally done with POSIXct classes) you could use as.POSIXct("23/8/22 12:45", format = "%d/%m/%y %H:%M"). This will make sure you keep information about the time from your string.
I have an imported CSV in R which contains a column of dates and times - this is imported into R as character. The format is "30/03/2020 08:59". I want to convert these strings into a format that allows me to work on them. For simplicity I have made a dataframe which has a single column of these dates (854) in this format.
I'm trying to use the parse_date_time function from lubridate.
It works fine when I reference a single value, e.g.
b=parse_date_time(consults_dates[3,1],orders="dmy HM")
gives b=2020-03-30 09:08:00
However, when I try to perform this on the entire(consults_dates), I get an error, e.g.
c= parse_date_time(consults_dates,orders="dmy HM") gives error:
Warning message:
All formats failed to parse. No formats found.
Apologies - if this is blatantly a simple question, day 1 of R after years of Matlab.
You need to pass the column to parse_date_time function and not the entire dataframe.
library(lubridate)
consults_dates$colum_name <- parse_date_time(consults_dates$colum_name, "dmy HM")
However, if you have only one format in the column you can use dmy_hm
consults_dates$colum_name <- dmy_hm(consults_dates$colum_name)
In base R, we can use :
consults_dates$colum_name <- as.POSIXct(consults_dates$colum_name,
format = "%d/%m/%Y %H:%M", tz = "UTC")
I have a question. I am downloading some data from mongodb and then I want to do sam calculations of this data. Unfortunately I get timestamp as a string I and don't know how to convert it back to timestamp.
MaxDate <- con_string$find(query = '{}', sort = '{"timestamp":-1}', limit = 1)$timestamp
Above code returns to me maximum date from column timestamp. But format of that is for me totally useful.
"Aug 14 2019 8:57AM"
Any ideas how to convert it to interpretable by R version of timestamp?
Update:
I
Here is a good link on how to modify strings to dates:
https://stats.idre.ucla.edu/r/faq/how-can-i-format-a-string-containing-a-date-into-r-date-object/
It has multiple formats you might want to compare with. For your specific example, I think this should work:
MaxDate <- as.Date(MaxDate, "%b %d %Y")
if you want to save the Date part only. If you also want to use the time, there is another method you could use for that:
strptime(temp, format="%b %d %Y %H:%M%p")
More information about as.Date() and formats you can find here: as.Date() helper
More information about strptime (date + time) you can find here: striptime helper
UPDATE: I found that package in R that might be helpful for you to avoid multiple conversions: timestamp conversions
You can cast the timestamp data to the measurable time stamp.
I have a data frame called RequisitionHistory2 with a variable called RequisitionDateTime and the levels are factors which look like 4/30/2019 14:16 I would like to split this into RequisitionDate and RequisitionTime in a datetime format.
I tried this code, but this still does not solve my issue with needing to split these into their own columns. The code also did not work as I got the error below.
mutate(When = as.POSIXct(RequisitionHistory2, format="%m/%d/%. %H:%M %p"))
Error in as.POSIXct.default(RequisitionHistory2, format = "%m/%d/%. %H:%M %p") : do not know how to convert 'RequisitionHistory2' to class “POSIXct”
I would like to have the variable RequisitionDateTime split into RequisitionDate and another variable RequisitionTime in the dataframe RequisitionHistory2. Any help is greatly appreciated!
Do not convert factors to datetime directly. You will need to convert it to a character first and then use a datetime function.
as.Date(as.character("10/25/2018"), format = "%m/%d/%Y")
would work for your date example.
library(lubridate)
mutate(df,When = mdy_hm(RequisitionHistory2))
If your datetime is in 4/30/2019 14:16 format
Note that as.POSIXct() works only on datetimes already in ISO 8601 format. I wrote a blog post about this and I think would be helpful for you to check out:
https://jackylam.io/tutorial/uber-data/
The anytime package ON CRAN directly converts from many formats, including factor and ordered to dates and datetime objects. It also heuristically tries a number of viable formats so that you do not need a format string. See the README at GitHub for an introduction, there is also a vignette
Your example works:
R> library(anytime)
R> anytime(as.factor("4/30/2019 14:16"))
[1] "2019-04-30 14:16:00 CDT"
R> anytime(as.factor("4/3/2019 14:16:17"), useR=TRUE)
[1] "2019-04-03 14:16:17 CDT"
R>
However, the underlying (Boost C++) parser does not like single digit days or month so you may need to flip back to R's parser via useR=TRUE as I did on the second example.
I am new to R and programming in general and am looking for help with writing a function with dates and times. I have checked around but am still a bit stuck.
Basically, I have dates in the format "dd/mm/YYYY HH:MM" and I have to calculate how much time has passed between various events.
I have given the following command (where "date" is the column in my data frame that indicates the date and time in the above format):
date=as.Date.factor(date,format="%d/%m/%Y %H:%M")
However, this displays only the date, without the time.
I also have tried:
date=substr(argo1$date,1,907)
And it shows the date and time.
However, when I try to find the difference between two dates i.e.the time that has passed with the command: difftime(date[2],date[3],unit="secs"), it returns that 0 seconds have passed.
When I try to find the difference with the command:
date[3]-date[2]
it tells me
Error in date[3] - date[2] : non-numeric argument to binary operator
The class(date) is "character".
Any idea what I am doing wrong?
Try strptime:
date1 = "30/12/2009 11:59"
date2 = "30/12/2009 12:03"
d1 = strptime(date1, "%d/%m/%Y %H:%M")
d2 = strptime(date2, "%d/%m/%Y %H:%M")
difftime(d1, d2, unit="secs")
# Time difference of -240 secs