2

I want to use the function datetime to display the time, but I am not able to. I kept getting 'TypeError: 'datetime.datetime' object is not callable'.Can someone please advise me how to solve this error.

from _datetime import datetime
class purchasDateTime:
    def __init__(self, datetime):
        self._datetime = datetime

    @property
    def datetime(self):
        return self._datetime

    def __str__(self):
        return 'Date&Time: {:%#d %b %Y %H:%M}'.format(self._datetime)


def main():
    t1 = purchasDateTime(datetime(2019,4,8,12,45))
    print(t1)
    print('Pickup time:',t1.datetime())

main()            

The result I want to get is "Pickup time: 12:45 PM"

Ever
  • 23
  • 1
  • 4

2 Answers2

1
@property
def datetime(self):
    return self._datetime

The purpose of the @property decorator is so you can refer to this as a property instead of a function, i.e. t1.datetime instead of t1.datetime().

TLDR: take off the parentheses ().

John Gordon
  • 29,573
  • 7
  • 33
  • 58
1

Use this:

print('Pickup time:', t1.datetime.strftime('%H:%M %p'))

It's a typo, because since you have a @property above your function, that function doesn't need to be called, just use it like a direct attribute, that's why you need to use the above code, your code should work fine now.

That said, i would recommend you to read:

How does the @property decorator work?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114