Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6861965
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T02:36:09+00:00 2026-05-27T02:36:09+00:00

I recently ran into a situatiton where I needed to subclass datetime.datetime and datetime.timedelta

  • 0

I recently ran into a situatiton where I needed to subclass datetime.datetime and datetime.timedelta in order to add a few methods. I immediately found, though, that any arithmetic operations would return a datetime.datetime object when I expected it to return a mydatetime.mydatetime instance instead. Below is the solution that a co-worker helped me out with for this problem. Does anyone have a more concise or convenient suggestion? Are there any dangers to what I have done here? Am I missing anything important?

from datetime import datetime, timedelta

def _to_mydatetime(native):
    '''Instantiates object of appropriate class based on class
    of the input object.'''
    if hasattr(native, 'timetuple'):
        return mydatetime(*native.timetuple()[:6])
    else:
        return mytimedelta(native.days, native.seconds)

class mydatetime(datetime):
    '''Subclass of datetime'''
    def __add__(self, other):
        result = super(mydatetime, self).__add__(other)
        return _to_mydatetime(result)

    def __sub__(self, other):
        result = super(mydatetime, self).__sub__(other)
        return _to_mydatetime(result)

class mytimedelta(timedelta):
    def __add__(self, other):
        result = super(mytimedelta, self).__add__(other)
        return _to_mydatetime(result)

    def __sub__(self, other):
        result = super(mytimedelta, self).__sub__(other)
        return _to_mydatetime(result)

    def __div__(self, other):
        result = super(mytimedelta, self).__div__(other)
        return _to_mydatetime(result)

    def __rmul__(self, other):
        result = super(mytimedelta, self).__rmul__(other)
        return _to_mydatetime(result)

    def __mul__(self, other):
        result = super(mytimedelta, self).__mul__(other)
        return _to_mydatetime(result)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T02:36:09+00:00Added an answer on May 27, 2026 at 2:36 am

    Well, this is the right way to do it (i’d just split the converter method into two). Python allows you to reduce code duplication though:

    from datetime import *
    
    def convproxy(methods,converter):
        def f(cls):
            def _proxyfactory(method):
                def _convproxy(self,*args,**kwargs):
                    return converter(getattr(super(cls,self),method)(*args,**kwargs))
                return _convproxy
            for m in methods:
                setattr(cls,m,_proxyfactory(m))
            return cls
        return f
    
    @convproxy(('__add__','__sub__'),lambda d:mydatetime(d.timetuple()[:6]))
    class mydatetime(datetime):
        pass
    
    @convproxy(('__add__','__sub__','__div__','__rmul__','__mul__'),\
            lambda t:mytimetuple(t.days,t.seconds))
    class mytimedelta(timedelta):
        pass
    

    The cryptic code under convproxy is just a smart-aleck way to generate the specified methods when creating a class, each of which calls a superclass method and creates a subclass from the result using the specified converter function.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've recently installed Windows 8 Dev preview, though I've ran into quite a few
Recently I've ran into some security issues where a cracker has found an exploit
I recently attempted to use selenium RC's GetAttribute method but immediately ran into a
I recently ran into a few problems with a third party vendor integration. In
I've been working a lot with the DateTime class and recently ran into what
A co-worker recently ran into a situation where a query to look up security
I recently ran into a problem that I thought boost::lambda or boost::phoenix could help
I recently ran into a issue where intermediate link betweeen a TCP server and
I recently ran into a problem with a COM object that was using a
I recently ran into an issue where a query was causing a full table

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.