如何在Ansible中将月份缩写转换为整数日期格式?
Got it, let's solve this date format shift in Ansible! You're working with a date string like '2020 Nov 19' and need to output it as '2020 11 19'—here are two reliable approaches to get this done.
Method 1: Use Ansible's Built-in Filters (Recommended)
Ansible has native strptime and strftime filters that make date parsing and formatting straightforward, no external dependencies needed.
Here's a quick playbook example:
- name: Convert date format with filters hosts: localhost vars: original_date: "2020 Nov 19" tasks: - name: Transform the date string debug: msg: "{{ original_date | strptime('%Y %b %d') | strftime('%Y %m %d') }}"
Breakdown of the filters:
strptime('%Y %b %d'): Parses your original string into a datetime object.%Y= 4-digit year (matches2020)%b= 3-letter abbreviated month (matchesNov)%d= 2-digit day (matches19)
strftime('%Y %m %d'): Formats the datetime object into your desired string.%m= 2-digit numeric month (turnsNovinto11)
This works across all platforms where Ansible runs, since it uses Python's datetime under the hood.
Method 2: Use the date Command (Shell Module)
If you need to rely on the target system's date utility (not recommended for cross-platform use), you can run a shell command to do the conversion:
- name: Convert date using shell command hosts: localhost vars: original_date: "2020 Nov 19" tasks: - name: Run date conversion command shell: date -d "{{ original_date }}" +"%Y %m %d" register: converted_date_result - name: Print converted date debug: msg: "{{ converted_date_result.stdout }}"
Note: This only works on systems with GNU date (like Linux). It won't work as-is on macOS or Windows, since their date commands have different syntax.
Quick Tips
- Double-check that your
strptimeformat string exactly matches the original date's structure. If your original date had lowercase months (e.g.,nov), you'd still use%b—it's case-insensitive in Python's parsing. - If your original date has single-digit days (e.g.,
2020 Nov 5),%dwill still parse it correctly, andstrftimewill output it as05if you need leading zeros.
内容的提问来源于stack exchange,提问作者VallingSki

