Calling class method inside string format

Viewed 582

Consider this:

from datetime import datetime

now = datetime.now() 
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22

'{0.strftime("%p")}'.format(now)
# gives
# AttributeError: 'datetime.datetime' object has no attribute 'strftime("%p")'

This seems to imply that I can't call a class method inside the format (I guess that's what strftime is).

What's a workaround for this (assuming I need to call the method inside the string, and keep using a format) ?

3 Answers

You could do this.

>>> from datetime import datetime
>>> now = datetime.now()
>>> '{0:%p}'.format(now)
'PM'

This will also work with f-strings.

>>> f"{now:%p}"
'PM'

You can use the f-string:

from datetime import datetime

now = datetime.now() 
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22

print(f'{now.strftime("%p")}')

Else:

from datetime import datetime

now = datetime.now() 
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22
print('{0:%p}'.format(now)) 

Documentation

You could use f-strings like this:

from datetime import datetime

now = datetime.now() 
now.strftime("%p")
print(f'{now.day}')

print(f'{now.strftime("%p")}')
Related