-1

I am new to R. I have a large data set with one of the columns containing a time stamp. The format of the column content is e.g. Sat Mar 07 18:38:01 EST 2015. Now I want to create an additional column in data frame with just date. All I care about in my second column is e.g. Mar 07 2015. I tried other similar questions but they are addressing a different format. Thanks in advance !

EDIT

The problem has been resolved. The best approach is to convert it into POSIXct object and then strip time or date off of it.

RforResearch
  • 401
  • 8
  • 16
  • @DirkEddelbuettel, although I wouldn't be surprised if this question is a duplicate, it seems like the linked answer doesn't cover the range of formatting issues in the OP's use case. – eipi10 Feb 08 '16 at 01:28
  • It doesn't matter. We have 1600 questions on `strptime`. Pick one. Any one. – Dirk Eddelbuettel Feb 08 '16 at 01:37

2 Answers2

1

This works for your example. Let me know if it works for your full data set:

x = "Sat Mar 07 18:38:01 EST 2015" 

as.Date(x, format="%a %b %d %H:%M:%S EST %Y")

[1] "2015-03-07"

See ?strptime for more information on all the formatting codes for parsing dates and times.

UPDATE: Per your comment, to add this to your data set: If your data frame is called df and your original column is timestamp then...

df$date = as.Date(df$timestamp, format="%a %b %d %H:%M:%S EST %Y")
eipi10
  • 91,525
  • 24
  • 209
  • 285
0

You can use format, as.Date, and strptime together:

x <- 'Sat Mar 07 18:38:01 EST 2015'

## Convert to date
y <- as.Date(strptime(x, '%a %b %d %H:%M:%S EST %Y'))
y
##[1] "2015-03-07"

## Change format
format(y, '%b %d %Y')
##[1] "Mar 07 2015"

## Do the whole thing in one line
format(as.Date(strptime(x, '%a %b %d %H:%M:%S EST %Y')), "%b %d %Y")
ytk
  • 2,787
  • 4
  • 27
  • 42