Skip to content

Instantly share code, notes, and snippets.

@SwampThingPaul
Last active August 2, 2021 19:04
Show Gist options
  • Select an option

  • Save SwampThingPaul/fb89e1dde9acc2cabac169c042316c44 to your computer and use it in GitHub Desktop.

Select an option

Save SwampThingPaul/fb89e1dde9acc2cabac169c042316c44 to your computer and use it in GitHub Desktop.
Date time fix for years with no prefix (ie century) Check out ?strptime and the %y format
# date.fun from personal AnalystHelper package
date.fun=function (x, tz = "EST", form = "%F"){as.POSIXct(strptime(x, form), tz = tz)}
# Example dataset
example=c("19-AUG-53 12.00.00.000000000 AM", "26-AUG-53 12.00.00.000000000 AM",
"26-AUG-53 12.00.00.000000000 AM", "26-AUG-53 12.00.00.000000000 AM",
"26-AUG-53 12.00.00.000000000 AM", "26-AUG-53 12.00.00.000000000 AM",
"01-APR-02 05.45.00.000000000 PM", "01-APR-02 12.00.00.000000000 AM",
"01-APR-02 12.00.00.000000000 AM", "01-APR-02 12.00.00.000000000 AM",
"01-APR-02 12.00.00.000000000 AM", "01-APR-02 12.00.00.000000000 AM")
# Split and recombine table to get a correctly formatted time.
spl=strsplit(example,split="-")
date_split=data.frame(SAMPLE_DATE=example,
day=sapply(spl,"[",1),month=sapply(spl,"[",2),yr_time=sapply(spl,"[",3))
date_split2=strsplit(date_split$yr_time,split=" ")
date_split=cbind(date_split[,1:3],data.frame(yr=sapply(date_split2,"[",1),time=sapply(date_split2,"[",2),AMPM=sapply(date_split2,"[",3)))
date_split$yr=with(date_split,ifelse(yr%in%seq(53,99,1),paste0("19",yr),paste0("20",yr)))
date_split$SAMPLE_DATE2=with(date_split,paste(paste(day,month,yr,sep="-"),time,AMPM))
date_split$datetime=date.fun(date_split$SAMPLE_DATE2,form="%d-%b-%Y %I.%M.%OS %p")
date_split[,c("SAMPLE_DATE","datetime")]
## END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment