Get Started

Date formats (1)

As you saw earlier, R is picky about how it reads dates. To remind you, as.Date("09/28/2008") threw an error because it was not in the correct format. The fix for this is to specify the format you are using through the format argument:

as.Date("09/28/2008", format = "%m / %d / %Y")
[1] "2008-09-29"

This might look strange, but the basic idea is that you are defining a character vector telling R that your date is in the form of mm/dd/yyyy. It then knows how to extract the components and switch to yyyy-mm-dd.

There are a number of different formats you can specify, here are a few of them:

  • %Y: 4-digit year (1982)
  • %y: 2-digit year (82)
  • %m: 2-digit month (01)
  • %d: 2-digit day of the month (13)
  • %A: weekday (Wednesday)
  • %a: abbreviated weekday (Wed)
  • %B: month (January)
  • %b: abbreviated month (Jan)

This is a part of the course

“Intermediate R for Finance”

View Course

Exercise instructions

In this exercise you will work with the date, "1930-08-30", Warren Buffett's birth date!

  • Use as.Date() and an appropriate format to convert "08,30,1930" to a date (it is in the form of "month,day,year").
  • Use as.Date() and an appropriate format to convert "Aug 30,1930" to a date.
  • Use as.Date() and an appropriate format to convert "30aug1930" to a date.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# "08,30,30"
as.Date("08,30,1930", format = ___)

# "Aug 30,1930"
as.Date("Aug 30,1930", format = ___)

# "30aug1930"
as.Date("30aug1930", format = ___)
Edit and Run Code

This exercise is part of the course

Intermediate R for Finance

BeginnerSkill Level
4.7+
11 reviews

Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.

Welcome! Before we go deeper into the world of R, it will be nice to have an understanding of how dates and times are created. This chapter will teach you enough to begin working with dates, but only scratches the surface of what you can do with them.

Exercise 1: An introduction to dates in RExercise 2: What day is it?Exercise 3: From char to dateExercise 4: Many datesExercise 5: Date formats and extractor functionsExercise 6: Date formats (1)
Exercise 7: Date formats (2)Exercise 8: Subtraction of datesExercise 9: months() and weekdays() and quarters(), oh my!

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free