Ruby strftime Format Directives Reference

Complete reference for Ruby's Time#strftime format directives. Covers percent-based tokens, padding modifiers, and differences from Python's strftime implementation.

Language-Specific

Detailed Explanation

Ruby strftime Directives

Ruby's Time#strftime and Date#strftime methods use percent-prefixed directives inherited from the C standard library, very similar to Python. However, Ruby includes several extra directives and modifier flags.

Core Directives

Directive Meaning Example
%Y Year (4-digit) 2026
%y Year (2-digit) 26
%m Month (zero-padded) 02
%-m Month (no padding) 2
%B Full month name February
%b / %h Abbreviated month Feb
%d Day (zero-padded) 28
%e Day (space-padded) 28
%-d Day (no padding) 28
%A Full weekday Saturday
%a Abbreviated weekday Sat
%u Weekday (1=Monday) 6
%w Weekday (0=Sunday) 6
%H Hour 24h (zero-padded) 14
%k Hour 24h (space-padded) 14
%I Hour 12h (zero-padded) 02
%l Hour 12h (space-padded) 2
%M Minute 30
%S Second 00
%L Millisecond 123
%N Nanosecond 123456789
%p AM/PM (uppercase) PM
%P am/pm (lowercase) pm
%j Day of year 059
%z Timezone offset +0900
%:z Offset with colon +09:00
%Z Timezone name JST
%s Unix timestamp 1772236800

Ruby-Specific Extras

Ruby includes directives not found in Python:

  • %e — Space-padded day ( 3 instead of 03)
  • %k — Space-padded 24h hour
  • %l — Space-padded 12h hour
  • %P — Lowercase am/pm (Python's %p is uppercase)
  • %L — Milliseconds (3 digits)
  • %N — Fractional seconds (up to 9 digits for nanoseconds)
  • %:z — Colon-separated offset (+09:00 vs +0900)
  • %s — Unix timestamp as string

Modifier Flags

Ruby supports modifier flags between % and the directive:

Flag Effect Example
- No padding %-d3
_ Space padding %_m 2
0 Zero padding (default) %0d03
^ Uppercase %^bFEB
# Case swap %#BFEBRUARY

Common Patterns

Time.now.strftime("%Y-%m-%d %H:%M:%S")        # "2026-02-28 14:30:00"
Time.now.strftime("%B %-d, %Y")                # "February 28, 2026"
Time.now.strftime("%a, %d %b %Y %H:%M:%S %z") # RFC 2822
Time.now.strftime("%Y-%m-%dT%H:%M:%S%:z")     # ISO 8601 with offset
Time.now.strftime("%I:%M %p")                  # "02:30 PM"
Time.now.strftime("%s")                        # Unix timestamp

Parsing with strptime

Time.strptime("2026-02-28 14:30", "%Y-%m-%d %H:%M")
Date.strptime("28/02/2026", "%d/%m/%Y")

Use Case

Ruby strftime is used in Rails view templates for date display, Active Record query scoping by date, Sidekiq job scheduling logs, API serializers (Jbuilder, ActiveModel::Serializer), rake task output, and DevOps scripts for log rotation and backup naming.

Try It — Date Format Reference & Tester

Open full tool