paretech
paretech

Reputation: 346

Why does subclass of datetime not an instance of subclass when specifying argument tz to method fromtimestamp?

Below is sample code that subclasses datetime.

Since pass is the only subclass body, method '__new__' of datetime is expected to be preserved.

The following code has been tested on Python 3.4.2 on Mac OS 10.12.3 and Python 3.6.0 on Arch Linux. In both cases, same result.

The question is, why is 'a' an instance of MyDatetime when 'b' is not an instance of MyDatetime when they differ only by argument tz?

Thank you for your feedback. Now on with the example...

#!/usr/bin/env python3

from datetime import datetime
from datetime import timezone

class MyDatetime(datetime):
    pass

if __name__ == '__main__':
    dt = 1231798102

    a = MyDatetime.fromtimestamp(dt)
    b = MyDatetime.fromtimestamp(dt, tz=timezone.utc)

    print('Why is isinstance(a, MyDatetime) == {}, while isinstance(b, MyDatetime) == {}?'.format(isinstance(a, MyDatetime), isinstance(b, MyDatetime)))

The above example prints the following: 'Why is isinstance(a, MyDatetime) == True, while isinstance(b, MyDatetime) == False?'

Here type(a) == <class '__main__.MyDatetime'>, while type(b) == <class 'datetime.datetime'>.

Upvotes: 1

Views: 236

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

Passing tz in MyDatetime.fromtimestamp(dt, tz=timezone.utc) invokes tz.fromutc in the implementation which returns a new datetime object ignoring the actual subclass you've created.

One, but I doubt the most effective way of assuring your class gets considered:

class MyDatetime(datetime):
    @classmethod
    def fromtimestamp(cls, t, tz=None):
        result = super().fromtimestamp(t, tz)
        if tz:
            print(result.strftime("%s"))
            return super().fromtimestamp(int(result.strftime("%s")))
        return result

Upvotes: 1

Related Questions