# strptime & strftime in R | 5 Example Codes (How to Set Year, Day, Hour & Time Zone)

In this article, Iâ€™ll explain how to convert characters to time objects (and the other way around). The tutorial is based on two R functions:

• strptime function (Examples 1-4)
• strftime function (Example 5)

The basic R syntax of the two functions looks as follows…

Basic R Syntax:

```strptime(character, format = "%Y-%m-%d") # Convert character to time object strftime(time) # Convert time object to character```

…and the definitions of the functions are as follows:

Definitions:

The strptime function converts characters to time objects.

The strftime function converts time objects to characters.

In this article, I’m going to show you five examples for the application of strptime and strftime in the R programming language.

Let’s dive into it…

## Example 1: Convert Character to Time Object in R (strptime Function)

Typically, the strptime R function is used to convert character objects to time objects. Before we start with the first example, let’s create an example character object:

`time_1 <- "2020-06-01" # Create example date as character`

Our example data consists of the date 2020-06-01 (i.e. 1st June of the Year 2020). However, right now our example date has the character class:

```class(time_1) # Class of example date # "character"```

We can use the R strptime function in order to transform this character string to a time object:

```time_1a <- strptime(time_1, # Apply strptime in R format = "%Y-%m-%d") time_1a # Print strptime output to console # "2020-06-01 CEST"```

As you can see, the output shown in the RStudio console is different – it is showing the time zone abbreviation CEST (i.e. Central European Summer Time).

Let’s check the class of our converted data:

```class(time_1a) # Class after applying strptime # "POSIXlt" "POSIXt"```

POSIXlt & POSIXt – the typical time classes of the R programming language (You can learn more about the different time classes here).

So far so good, so how can we modify the time object according to our specific needs? That is what I’m going to show you in Example 2, 3, and 4…

## Example 2: Time Object With Time Zone

A typical issue of time variables is the time zone that is stored in R. Make a quick Google search:

Figure 1: Time Zones of the USA.

The USA alone has 4 different time zones, and then you also need to consider summer and winter time…

However, in R it is very easy to set the time zone as you want. Just use the tz option within the strptime function:

```time_1b <- strptime(time_1, # Apply strptime with timezone format = "%Y-%m-%d", tz = "EST") time_1b # Print strptime output to console # "2020-06-01 EST"```

## Example 3: Time Object With Hour, Minute & Second

Another important part of time objects (and the main distinction to the as.Date function) is the possibility to extend these time objects by days, hours, minutes and so on.

Let’s create another example character that contains such information:

`time_2 <- "2020-06-01 16:15:10" # Create second example date`

And now let’s apply the strptime function accordingly:

```time_2a <- strptime(time_2, # Apply strptime with timezone format = "%Y-%m-%d %H:%M:%OS", tz = "EST") time_2a # Print strptime output to console # "2020-06-01 16:15:10 EST"```

Note: We extended the format option with %H:%M:%S in order to display hour, minute and second as well.

Can we extent this even more? Yes, we can!

## Example 4: Time Object With Milliseconds

First, let’s create another example character that contains milliseconds:

`time_3 <- "2020-06-01 16:11:00.255" # Create third example date`

To add milliseconds to a time object, we have to modify the format option again (i.e. format = “… %OS):

```time_3a <- strptime(time_3, # Apply strptime with timezone format = "%Y-%m-%d %H:%M:%OS", tz = "EST") time_3a # Print strptime output to console # "2020-06-01 16:15:10 EST"```

As you can see, however, the R code is not working yet. If we want to add milliseconds to a time object, we have to apply a little trick:

The default options of R are is set to show 0 millisecond digits. For that reason we need to update the global R options as follows:

`options(digits.secs = 3) # Change global R options`

Now, we can apply the strptime function again:

```time_3a # Output after modifying options # "2020-06-01 16:15:10.255 EST"```

Et voilÃ  – The milliseconds are shown!

Don’t forget to set the global options back to zero milliseconds, in case you don’t want to use the modified global options for the rest of your R session:

`options(digits.secs = 0) # Set global options back to default`

Now, what if we want to convert time objects to characters? That’s what I’m going to show you next:

## Example 5: Convert Time Object to Character in R (strftime Function)

In order to change the class of a time object to character, we have to use the strftime R function (with an f instead of a p in the middle).

Let’s use our previously created time object time_3a for this example:

```class(time_3a) # Check class of data object # "POSIXlt" "POSIXt"```

No surprise: our example data has the typical time classes POSIXlt & POSIXt. Now, let’s use the strftime command to convert our data back to character:

```time_3b <- strftime(time_3a) # Apply strftime function time_3b # Print strftime output to console # "2020-06-01 16:11:00"```

Looks good. And what about the class?

```class(time_3b) # Check class after applying strftime # "character"```

Looks good as well.

## Calculate Difference Between Time Objects in R (Video)

So far, we have only learned how to convert time objects. However, sometimes you might need to calculate the time difference between several dates. This can be easily done with the difftime function, a function that I’m explaining in another R tutorial, which you can check out here.

You can also have a look at the following YouTube video of Mr. Math Expert. In the video he is showing several ways how to calculate the difference between time and date objects.

Have fun with the video and let me know in the comments, in case you have further questions!

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

## Further Reading

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

#### 2 Comments.Leave new

• Natalie Marshall
October 14, 2020 2:49 am

I want to convert a date to a week number: 2019-01-01 (POSIXct) to factor or character, eg 1, 2, 3, …, so I can overlay one set of weeks in one year with the same set of weeks in the next year.

Reply
• Hey Natalie,

Thank you for the interesting question.

You may have a look at this thread on Stack Overflow. I think it is answering your question. Specifically, this code provided by mpalanco:

`strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%V")`

I hope that helps!

Joachim

Reply
Menu
Top