You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible中将月份缩写转换为整数日期格式?

Ansible Date Format Conversion: '2020 Nov 19' → '2020 11 19'

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.

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 (matches 2020)
    • %b = 3-letter abbreviated month (matches Nov)
    • %d = 2-digit day (matches 19)
  • strftime('%Y %m %d'): Formats the datetime object into your desired string.
    • %m = 2-digit numeric month (turns Nov into 11)

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 strptime format 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), %d will still parse it correctly, and strftime will output it as 05 if you need leading zeros.

内容的提问来源于stack exchange,提问作者VallingSki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:17:46