20

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.

Sam Morgan
  • 2,445
  • 1
  • 16
  • 25

4 Answers4

65

There's a native way:

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

More on that:

George Sovetov
  • 4,942
  • 5
  • 36
  • 57
12
print(f'Updated {date.today().strftime("%m/%d/%Y")}')

Your code was prematurely ending the string definition.

Rich Tier
  • 9,021
  • 10
  • 48
  • 71
3

if string is part of another string you need to use double quote in one of them

(f"updated {date.today().strftime('%D')}") # %m/%d/%y can also be written %D
  • escaping the (inner) single quotes would also work, though there's no reason to prefer that here. `f'updated {date.today().strftime(\'%D\')}'` – Adam Smith Nov 12 '18 at 21:05
  • Ah, nice tip on %D. Where did you find this? I can't find that reference anywhere in documentation. – Sam Morgan Nov 14 '18 at 18:54
  • 3
    i found it here ' https://www.tutorialspoint.com/python/time_strftime.htm ' some of which are not in documentation i guess – ratan kamath Nov 15 '18 at 06:06
2

Strangely this has not been proposed:

print(date.today().strftime("Updated: %m/%d/%Y"))
Paal Pedersen
  • 1,070
  • 1
  • 10
  • 13