Leading 0 on now().month in Jinja2 templating

hi,
I guess this problem has been fixed before. Unfortunately I can’t get my head around it.
Goal:
I want to save a file in the fomat myfile-yyyymmdd-hhmmss.jpg
I found:
myfile-{{ now().year }}{{ now().month }}{{ now().day }}-{{ now().hour }}{{ now().minute }}{{ now().second }}.jpg"
Problem:
Those conversions do not add leading 0’s. e.g. for the month September, now().month returns 9, where I would need (expect) 09
I tried with:
now() | datetimeformat('...'), but the filter datetimeformat is not allowed for “now()”. Frankly, it is not clear to me what the format is of “now()”
I also tried with:
{{now().month|pad(2)}, but that seems also to be an invalid statement

Any tips would be welcome
thanks,
chrisV

1 Like

myfile-{{ now().strftime('%Y%m%d-%H%M%S') }}.jpg

wel I’ll be d*
as simple as that… and it worked right away
I was searching for jinja2 filters, …and I did read the documentation, both of them: the HomeAsistant docs and the Jinja2 docs.
Now this turns out to be python ?
How does that work?
Anyway. A big thank you Phil @pnbruckner

I can’t explain it fully, other than to say that Jinja is implemented in Python. I’ve just found over time that if you have a Python object (which is what now() returns – specifically, a datetime object), then you can use its Python methods.

I guess to do it the “official” way would be something like this:

myfile-{{ as_timestamp(now())|timestamp_custom('%Y%m%d-%H%M%S') }}.jpg

You can also use python’s format to get the job done … but for this application it’s not nearly as compact as Phil’s solution.

{{'myfile-{}{:02d}{:02d}-{:02d}{:02d}{:02d}.jpg'.format(now().year, now().month, now().day, now().hour, now().minute, now().second) }}

nice. Thank you @123 and @pnbruckner