convert character to 12H time format in R - r

I need to convert a time in character "01:15:55 AM" to time.
I was thinking of using chron library, however I am not sure how to do the format.
chron(times = "01:15:55 AM", format = "%I:%M:%S %p")
Error in parse.format(format) : unrecognized format %I:%M:%S %p
Any ideas? I'm happy to try other libraries

One option is to use strptime to parse, and then format the result so you can make it into a nice chron::times object:
library(chron)
times(format(strptime("01:15:55 PM", format = "%I:%M:%S %p"), "%H:%M:%S"))
# [1] 13:15:55

testtime<-("2013-07-21 02:00:01 PM")
library(lubridate)
ymd_hms(testtime)
[1] "2013-07-21 14:00:01 UTC"

The canonical way of dealing with date and time objects in R is using the POSIX functions, such as:
> (time.POSIX<-strptime("01:15:55 AM", format = "%I:%M:%S %p"))
[1] "2016-03-31 01:15:55 BRT"
> class(time.POSIX)
[1] "POSIXlt" "POSIXt"
The strptime function, along with all others that work with POSIX dates, such as format (for printing) accept the format string that you're using.
The problem here is that this data is not a time per se, but a date and a time, and the date part is implicitly created as "today". So you can create this time objects in a fixed reference date, say, 2000-01-01.
On the other hand, if you want to use the chron package... they are not compliant with these format specifications. chron manual only specifies m, d, y, h, m and s.
You might have to write a wrapper that understands AM/PM and fixes it.

Related

reformatting datetime in R

I have data "A" in the format chr "5/7/2021 15:15". I would like to convert it to a format which R will recognize. (It is giving me errors when I try to plot, for instance, which leads me to believe it needs to be reformatted.)
Here is the format "B" I would like to achieve. R seems to like this ok, so I might as well match it (?):
POSIXct, format: "2021-8-11 16:00:00". I am not sure if the seconds are needed, and they do not exist in data "A" so the seconds could be omitted. If R doesn't care then I don't either. The timezone is UTC.
How do I do it? I have tried a couple things, including:
CTD_datetime_UTC <- as.POSIXct(CTD$Date.and.Time, tz = "UTC").
You can use strptime from base R. But there are many parsers for dates...
Assuming the format is "day/month/year" (example is not unambiguous, could also be "month/day/year")
strptime("5/7/2021 15:15", "%d/%m/%Y %H:%M", tz = "UTC")
Returns:
[1] "2021-07-05 15:15:00 UTC"
Using parsedate
library(parsedate)
parse_date("5/7/2021 15:15")
[1] "2021-05-07 15:15:00 UTC"

Convert Character date/time with am and pm to date/time format

I am attempting to convert a character date time to a date/time format using strptime. The data is in MDY_HM (1/29/20 3:43pm).
My code currently looks like this:
comp_report_tz$Start_Date_Time <- strptime(comp_report_tz$Start_Date_Time, format = "%m/%d/%y %H:%M %p")
The output for each observation simply shows: "< POSIXlt >"
I don't receive any errors when executing.
Make the following changes:
use %I for the hour
use %p for the am/pm.
ensure that the format pattern is in the precise pattern of the data -- it's not in the question
you likely want POSIXct, not POSIXlt
thus we use this format
as.POSIXct("1/29/20 3:43pm", format = "%m/%d/%y %I:%M%p")
## [1] "2020-01-29 15:43:00 EST"

Convert chron to POSIXct in GMT format

Normally, I use chron to represent date/time objects. However, I need to use some functions that work with the POSIX format, so I am trying to go from chron to POSIXct. Using as.POSIXct() seems to work but the result is in localtime instead of GMT (the original data is in GMT).
x <- chron(dates="05/12/15", times="12:30:45")
as.POSIXct(x, tz="GMT")
"2015-05-12 13:30:45 BST"
what I want is:
"2015-05-12 12:30:45 GMT"
but I can't find a way to obtain it.
strptime() won't work because the original input is not a string, but a chron object. Of course I could go from a chron object to a character string and then to POSIXct but it seems a bit convoluted way to do it.
I suppose I could force my R session to use GMT with Sys.timezone(), but I'd prefer not to. Any other suggestion? Thank you.
Just try:
x <- chron(dates="05/12/15", times="12:30:45")
y<-as.POSIXct(x)
attr(y,"tzone")<-"GMT"
y
#[1] "2015-05-12 12:30:45 GMT"

R lubridate converting seconds to date

I have a simple question regarding R's lubridate package. I've a series of timestamps in seconds since epoch. I want to convert this to YYYY-MM-DD-HH format. In base R, I can do something like this to first convert it to a date format
> x = as.POSIXct(1356129107,origin = "1970-01-01",tz = "GMT")
> x
[1] "2012-12-21 22:31:47 GMT"
Note the above just converts it to a date format, not the YYYY-MM-DD-HH format. How would I do this in lubridate? How would I do it using base R?
Thanks much in advance
lubridate has an as_datetime() that happens to have UNIX epoch time as the default origin time to make this really simple:
> as_datetime(1356129107)
[1] "2012-12-21 22:31:47 UTC"
more details can be found here: https://rdrr.io/cran/lubridate/man/as_date.html
Dirk is correct. However, if you are intent on using lubridate functions:
paste( year(dt), month(dt), mday(dt), hour(dt) sep="-")
If on the other hand you want to handle the POSIXct objects the way they were supposed to be used then this should satisfy:
format(x, format="%Y-%m-%d-%H")
I use the lubridate solution provided by #leerssej
But in case anyone prefers #IRTFM's solution in base R, but also wants minutes and seconds, here's an example of how to do that:
as.POSIXct("2019-03-15 16:17:42" , format="%Y-%m-%d %H:%M:%OS")

Convert date-time string to class Date

I have a data frame with a character column of date-times.
When I use as.Date, most of my strings are parsed correctly, except for a few instances. The example below will hopefully show you what is going on.
# my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
str_locate(prods.all$Date, " ")[1]-1),
"%m/%d/%Y")
# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
# Date Date2
# 1925 10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15
As you can see, the year of some of the dates is inaccurate. The pattern seems to occur when the day is double digit.
Any help you can provide will be greatly appreciated.
The easiest way is to use lubridate:
library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)
This function automatically returns objects of class POSIXct and will work with either factors or characters.
You may be overcomplicating things, is there any reason you need the stringr package? You can use as.Date and its format argument to specify the input format of your string.
df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
as.Date(df$Date, format = "%m/%d/%Y %H:%M:%S")
# [1] "2009-10-09" "2009-10-15"
Note the Details section of ?as.Date:
Character strings are processed as far as necessary for the format specified: any trailing characters are ignored
Thus, this also works:
as.Date(df$Date, format = "%m/%d/%Y")
# [1] "2009-10-09" "2009-10-15"
All the conversion specifications that can be used to specify the input format are found in the Details section in ?strptime. Make sure that the order of the conversion specification as well as any separators correspond exactly with the format of your input string.
More generally and if you need the time component as well, use as.POSIXct or strptime:
as.POSIXct(df$Date, "%m/%d/%Y %H:%M:%S")
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
I'm guessing at what your actual data might look at from the partial results you give.
If you don't know the format you could use anytime::anydate, which tries to match to common formats:
library(anytime)
date <- c("01/01/2000 0:00:00", "Jan 1, 2000 0:00:00", "2000-Jan-01 0:00:00")
anydate(date)
[1] "2000-01-01" "2000-01-01" "2000-01-01"
library(lubridate)
if your date format is like this '04/24/2017 05:35:00'then change it like below
prods.all$Date2<-gsub("/","-",prods.all$Date2)
then change the date format
parse_date_time(prods.all$Date2, orders="mdy hms")

Resources