2

With datetime objects, you can use .format in a special way:

from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(1990, 4, 28, 22, 30))

Those are the usual formatters for datetime objects.

Can I give any class such custom ways to format them? How?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • The dupe target refers to string formatting only. This question seems to be for an object of arbitrary class, although the title makes it sound like it's about `datetime`. I'd say this isn't a dupe, but the title should be edited. – C8H10N4O2 Aug 09 '17 at 19:07
  • @C8H10N4O2 I tried improve the title. – Martin Thoma Aug 09 '17 at 19:13
  • 1
    @C8H10N4O2 https://stackoverflow.com/a/19864463/846892. `__format__` is decently known, you could find more dupes easily, for example: https://stackoverflow.com/q/28904602/846892 – Ashwini Chaudhary Aug 09 '17 at 19:16

1 Answers1

2

Just found the answer on https://pyformat.info/:

Yes

class HAL9000(object):

    def __format__(self, format):
        if (format == 'open-the-pod-bay-doors'):
            return "I'm afraid I can't do that."
        return 'HAL 9000'
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958