Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 259
Sam Morgan Avatar asked Nov 12 '18 20:11

Sam Morgan


Video Answer


1 Answers

There's a native way:

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

More on that:

  • PEP 3101 -- Advanced String Formatting -- Controlling Formatting on a Per-Type Basis
  • datetime.date.__format__
like image 53
George Sovetov Avatar answered Oct 04 '22 20:10

George Sovetov