Search code examples
pythonpython-3.xstring-formattingf-string

Python f-string formatting not working with strftime inline


I'm hitting an odd error that I'm trying to understand. Doing some general code cleanup and converting all string formatting to f-strings. This is on Python 3.6.6

This code does not work:

from datetime import date
print(f'Updated {date.today().strftime('%m/%d/%Y')}')

  File "<stdin>", line 1
    print(f'Updated {date.today().strftime('%m/%d/%Y')}')
                                               ^
SyntaxError: invalid syntax

However, this (functionally the same) does work:

from datetime import date
d = date.today().strftime('%m/%d/%Y')
print(f'Updated {d}')

Updated 11/12/2018

I feel like I'm probably missing something obvious, and am fine with the second iteration, but I want to understand what's happening here.


Solution

  • There's a native way:

    print(f'Updated {date.today():%m/%d/%Y}')
    

    More on that: