Ansible strftime Filter: Format Dates and Timestamps in Playbooks
By Luca Berton · Published 2024-01-01 · Category: web-servers
Complete guide to Ansible strftime filter. Format dates, timestamps, and ansible_date_time facts with custom patterns. Create backup filenames and log entries.
What Is the strftime Filter?
The strftime filter formats Unix timestamps into human-readable date strings using Python's strftime directives. It's essential for creating timestamped backups, log entries, and dynamic filenames.
Basic Usage
Common Format Directives
| Directive | Meaning | Example | |-----------|---------|---------| | %Y | 4-digit year | 2026 | | %m | Month (01-12) | 04 | | %d | Day (01-31) | 25 | | %H | Hour 24h (00-23) | 14 | | %M | Minute (00-59) | 30 | | %S | Second (00-59) | 45 | | %A | Weekday name | Friday | | %B | Month name | April | | %b | Month abbreviation | Apr | | %I | Hour 12h (01-12) | 02 | | %p | AM/PM | PM | | %Z | Timezone name | UTC | | %j | Day of year (001-366) | 115 | | %U | Week number (00-53) | 16 |
Practical Examples
Timestamped Backup Filenames
Log Entries with Timestamps
Archive with Date
Using ansible_date_time Facts
The ansible_date_time fact provides pre-formatted date/time values:
Format ansible_date_time.epoch
Calculate Future/Past Dates
Conditional Based on Time
Ansible now() Function
Since Ansible 2.8, you can use now() for the current time:
FAQ
What is the difference between strftime and ansible_date_time?
strftime is a filter that formats timestamps with custom patterns. ansible_date_time is a fact gathered at playbook start containing pre-formatted date/time values. Use ansible_date_time for common formats and strftime for custom patterns.
How do I convert a date string to epoch in Ansible?
Use the to_datetime filter: {{ '2026-04-25' | to_datetime('%Y-%m-%d') }}. To get epoch seconds, chain with strftime: {{ ('2026-04-25' | to_datetime('%Y-%m-%d')).strftime('%s') }}.
Why does ansible_date_time show the wrong timezone?
ansible_date_time uses the target host's timezone. Set the TZ environment variable or use now(utc=true) for UTC. For a specific timezone, configure it on the target host with timedatectl set-timezone.
Related Articles • ansible_date_time Facts Guide • Ansible Jinja2 Filters • Ansible set_fact Module • Ansible Template Module
Category: web-servers