Get Started

Create and format times

Similar to working with dates, you can use as.POSIXct() to convert from a character string to a POSIXct object, and format() to convert from a POSIXct object to a character string. Again, you have a wide variety of symbols:

  • %H: hours as a decimal number (00-23)
  • %I: hours as a decimal number (01-12)
  • %M: minutes as a decimal number
  • %S: seconds as a decimal number
  • %T: shorthand notation for the typical format %H:%M:%S
  • %p: AM/PM indicator

For a full list of conversion symbols, consult the strptime documentation in the console:

?strptime

Again,as.POSIXct() uses a default format to match character strings. In this case, it's %Y-%m-%d %H:%M:%S. In this exercise, abstraction is made of different time zones.

This is a part of the course

“Intermediate R”

View Course

Exercise instructions

  • Convert two strings that represent timestamps, str1 and str2, to POSIXct objects called time1 and time2.
  • Using format(), create a string from time1 containing only the minutes.
  • From time2, extract the hours and minutes as "hours:minutes AM/PM". Refer to the assignment text above to find the correct conversion symbols!

Hands-on interactive exercise

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

# Definition of character strings representing times
str1 <- "May 23, '96 hours:23 minutes:01 seconds:45"
str2 <- "2012-3-12 14:23:08"

# Convert the strings to POSIXct objects: time1, time2
time1 <- as.POSIXct(str1, format = "%B %d, '%y hours:%H minutes:%M seconds:%S")


# Convert times to formatted strings
Edit and Run Code

This exercise is part of the course

Intermediate R

BeginnerSkill Level
4.5+
132 reviews

Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.

Mastering R programming is not only about understanding its programming concepts. Having a solid understanding of a wide range of R functions is also important. This chapter introduces you to many useful functions for data structure manipulation, regular expressions, and working with times and dates.

Exercise 1: Useful FunctionsExercise 2: Mathematical utilitiesExercise 3: Find the errorExercise 4: Data UtilitiesExercise 5: Find the error (2)Exercise 6: Beat Gauss using RExercise 7: Regular ExpressionsExercise 8: grepl & grepExercise 9: grepl & grep (2)Exercise 10: sub & gsubExercise 11: sub & gsub (2)Exercise 12: Times & DatesExercise 13: Right here, right nowExercise 14: Create and format datesExercise 15: Create and format times
Exercise 16: Calculations with DatesExercise 17: Calculations with TimesExercise 18: Time is of the essence

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