[R] strftime - Dates from Excel files

Mikko Korpela mikko.korpela at aalto.fi
Fri Feb 3 15:25:46 CET 2012


On 02/03/2012 03:34 PM, Ana wrote:
> Hi
> 
> I have many excel files were the Date field was not declared as date,
> so the dates look like this: 1/2/1978
> I know that the format is day/month/year
> 
> How can I make R change this to Date format?
> 
> If I use strftime, I get wrong dates:
> 
> dataset=c("1/2/1978")
> 
> strftime(dataset,"%d/%m/%Y")
> "19/02/0001"

Hi!

Prof. Ripley already provided a nice, concise answer, but here's a more
verbose one.

The function strftime() is used for output formatting. In your example,
"%d/%m/%Y" is the chosen output format. Use strptime() for converting
character vectors (i.e. text input) to class "POSIXlt". For converting
to class "Date", use as.Date(). These are alternative classes for
representing dates in R.

> strptime(dataset, format="%d/%m/%Y")
[1] "1978-02-01"

> as.Date(dataset, format="%d/%m/%Y")
[1] "1978-02-01"

For converting "POSIXlt" or "Date" back to a character representation,
use as.character() or, for a customizable style, format().

> format(strptime(dataset, format="%d/%m/%Y"), "%a %b %d, %Y")
[1] "Wed Feb 01, 1978"

-- 
Mikko Korpela
Aalto University School of Science
Department of Information and Computer Science



More information about the R-help mailing list