[R] Time and date conversion

peter dalgaard pd@|gd @end|ng |rom gm@||@com
Mon Jun 4 12:54:26 CEST 2018



> On 4 Jun 2018, at 10:45 , Christofer Bogaso <bogaso.christofer using gmail.com> wrote:
> 
> Hi,
> 
> I have an automatic data feed and I obtained a Date vector in the following
> format:
> 
>> Date
> [1] "03 Jun 2018 10:01 am CT"    "01 Jun 2018 22:04:25 pm CT"
> 
> I now like to convert it to UTC time-zone
> 
> Is there any easy way to convert them so, particularly since 1st element
> doesnt have any Second element whereas the 2nd element has.

..and it also mixes up am/pm notation and 24hr clock.

There are two basic approaches to the format inconsistency thing:

(A) preprocess using gsub() constructions 

> gsub(" (..:..) ", " \\1:00 ", d.txt)
[1] "03 Jun 2018 10:01:00 am CT" "01 Jun 2018 22:04:25 pm CT"

(B) Try multiple formats

> d <- strptime(d.txt, format="%d %B %Y %H:%M:%S %p")
> d[is.na(d)] <- strptime(d.txt[is.na(d)], format="%d %B %Y %H:%M %p")
> d
[1] "2018-06-03 10:01:00 CEST" "2018-06-01 22:04:25 CEST"

I would likely go for (A) since you probably need to do something gsub-ish to get the TZ thing in place.

-pd

> 
> Thanks for any pointer.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes using cbs.dk  Priv: PDalgd using gmail.com




More information about the R-help mailing list