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).
strftime
What's a workaround for this (assuming I need to call the method inside the string, and keep using a format) ?
You could do this.
>>> from datetime import datetime >>> now = datetime.now() >>> '{0:%p}'.format(now) 'PM'
This will also work with f-strings too.
f
>>> f"{now:%p}" 'PM'
2.1m questions
2.1m answers
60 comments
57.0k users