Post

Using strftime for Date Formatting

For some reason when I’m working with dates in Ruby or R, I forget that there is a super handy method that can be used to format a date, or even a string, so that it looks completely different.

Most recently, I was working in R to convert a date object from the Sys.Date(), which returns 2023-03-17 into “Friday, March 17, 2023”.

I put together this complex line of code to get what I needed. Deep down, I knew that it was super inefficient.

paste0(weekdays(Sys.Date()), ", ", months(Sys.Date()), " ", format(Sys.Date(), "%d"), ", ",format(Sys.Date(), "%Y"))

I posed my question to the #rstats community on Mastodon and got a super helpful response in return. That’s when I started to feel really embarrassed. I wrote something that used part of the solution over and over in the concatenation method (paste0()) that was completely useless.

The person who responded, converted my super long string into a short and sweet string using R’s implementation of strftime:

format(Sys.Date(), format = '%A, %B %d, %Y')

Screenshot from Mastodon showing my question and a response from another user with a better solution.

Most languages have strftime baked into the codebase. In R, you use the format() method. In Ruby, as well as other programming languages, you simply call strftime(...) on the object and pass in some options.

What is strftime?

strftime is a method in Ruby’s Time class that allows you to format a time object as a string according to a given format. The name “strftime” stands for “string format time,” and it’s a powerful tool for working with dates and times in your code.

Let’s take a look at some examples of how to use strftime in Ruby.

Basic usage

The simplest way to use strftime is to call it on a Time object and pass in a format string. The format string tells strftime how to format the time object as a string. Here’s an example:

1
2
3
time = Time.now
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S")
puts formatted_time

This code will output the current date and time in the format "YYYY-MM-DD HH:MM:SS". The format string uses various format specifiers to represent different parts of the time object. For example, %Y represents the year with century as a decimal number, %m represents the month as a zero-padded decimal number, and %S represents the second as a zero-padded decimal number.

Custom formats

You can create custom format strings to display dates and times in any format you want. For example, if you want to display the weekday as a string, or display the time in 12-hour format with AM/PM indicators.

The neat thing about the options string that you pass in, is that you can delimit it using whatever character suits your needs. You can use dashes, slashes, spaces, letters, etc.

Here are some examples of custom format strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
time = Time.now

# Display the day of the week as a string
time.strftime("%A")  # "Wednesday"

# Display the time in 12-hour format with AM/PM indicators
time.strftime("%I:%M:%S %p")  # "03:25:45 PM"

# Display the date in mm/dd/yyyy format as a string
time.strftime("%M-%d-%Y")  # "03/17/2023"

# Similar to the statement above but with two digit year
time.strftime("%D") # "03/17/23"

# Display the month and four digit year
time.strftime("%B %Y") # "March 2023"

# Display the date in a long format
time.strftime("%A, %B %d, %Y") # Friday, March 17, 2023

There are many different parameters (format specifiers) that you can pass in to format the date object . All available options can be found in the Time#strftime ruby docs.

Below are some of the most common options that can be passed in to the strftime method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
%a: The abbreviated weekday name (e.g. "Sun", "Mon", etc.).
%A: The full weekday name (e.g. "Sunday", "Monday", etc.).
%b: The abbreviated month name (e.g. "Jan", "Feb", etc.).
%B: The full month name (e.g. "January", "February", etc.).
%c: The preferred local date and time representation.
%C: The century number (e.g. "20" for the year 2022).
%d: The day of the month as a zero-padded decimal number (e.g. "01" to "31").
%D: The same as "%m/%d/%y".
%e: The day of the month as a blank-padded decimal number (e.g. " 1" to "31").
%F: The same as "%Y-%m-%d".
%g: The last two digits of the year (e.g. "22" for the year 2022).
%G: The year with century as a decimal number (e.g. "2022").
%h: The same as "%b".
%H: The hour (24-hour clock) as a zero-padded decimal number (e.g. "00" to "23").
%I: The hour (12-hour clock) as a zero-padded decimal number (e.g. "01" to "12").
%j: The day of the year as a zero-padded decimal number (e.g. "001" to "366").
%m: The month as a zero-padded decimal number (e.g. "01" to "12").
%M: The minute as a zero-padded decimal number (e.g. "00" to "59").
%n: A newline character.
%p: "AM" or "PM" in uppercase.
%P: "am" or "pm" in lowercase.
%r: The time in 12-hour notation (e.g. "01:23:45 PM").
%R: The time in 24-hour notation (e.g. "13:23").
%s: The number of seconds since the Epoch (January 1, 1970 UTC).
%S: The second as a zero-padded decimal number (e.g. "00" to "59").
%t: A tab character.
%T: The same as "%H:%M:%S".
%u: The weekday as a decimal number (1-7), with 1 representing Monday.
%U: The week number of the year (Sunday as the first day of the week) as a zero-padded decimal number (e.g. "00" to "53").
%V: The ISO 8601 week number of the year (Monday as the first day of the week) as a zero-padded decimal number (e.g. "01" to "53").
%w: The weekday as a decimal number (0-6), with 0 representing Sunday.
%W: The week number of the year (Monday as the first day of the week) as a zero-padded decimal number (e.g. "00" to "53").
%x: The preferred local date representation.
%X: The preferred local time representation.
%y: The year without century as a zero-padded decimal.
%Y: The year with century if provided, will pad result at least 4 digits.

Additionally, if you’d rather not memorize all of the options that can be passed in, check out the [strftime.net] website. It allow you to click on the items and builds the option list for you.

Conclusion

strftime is a powerful method for working with dates and times in many programming languages. It allows you to format time objects as strings in any format you want. By mastering strftime, you’ll be able to manipulate dates and times in your code with ease.

Note to self: stop forgetting about strptime and start formatting your date objects efficiently!

This post is licensed under CC BY 4.0 by the author.