#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2

    Problems with datetime(again)


    So awhile ago I asked a question in regards to datetime instantiation and the result I have seemed satisfactory enough...

    and then I didn't check it. I got bored and moved on. I have ADD. :P

    So yeah, here's the code I got presently:

    Code:
    class timestamp(datetime.datetime):
    	def __repr__(self):
    		pm,hour = divmod((self.hour),12)
    		pm = bool(pm)
    		timestring = (str(hour)+':'+str(self.minute).zfill(2)+':'+str(self.second).zfill(2))
    		if pm:
    			timestring += 'PM'
    		else:
    			timestring += 'AM'
    		datestring = (str(self.month)+'-'+str(self.day)+'-'+str(self.year))
    		if glob.long_forms:
    			wdformat = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 
    
    5:'Saturday', 6:'Sunday'}
    		else:
    			wdformat = {0:'Mon', 1:'Tue', 2:'Wed', 3:'Thu', 4:'Fri', 5:'Sat', 6:'Sun'}
    		if glob.show_weekday:
    			weekday = wdformat[now.weekday()]
    			ret += self.weekday()
    		else:
    			return datestring+','+timestring
    	def __init__(self,**kwargs):
    		if not kwargs:
    			kwargs = {"year"		: datetime.datetime.now().year,
    				"month"			: datetime.datetime.now().month,
    				"day"			: datetime.datetime.now().day,
    				"hour"            	: datetime.datetime.now().hour,
    				"minute"		: datetime.datetime.now().minute,
    				"second"		: datetime.datetime.now().second,
    				"millis"		: datetime.datetime.now().millisecond}
    		self.__dict__ = process(self.__dict__,kwargs)
    	def process(defargs,kwargs):
    		for kwarg in kwargs:
    			if kwarg in defargs:
    				defargs[kwarg] = kwargs[kwarg]
    			else:
    				raise AttributeError("Invalid keyword: {}".format(kwarg))
    			return defargs
    And to make it run (although this isn't how I have it working in my code, this is a throwback to my old method) you would need something like:

    Code:
    class glob():
    	long_forms=False
    	show_weekday=True
    Thing is, it doesn't process the default arguments until AFTER it's called the initializer and so I get an error. :\
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480

    At a glance


    What is the question? Please present code that does something more than compiles.

    Problems with the program:
    • You've used tabs to indent the code. That's trouble.
    • process handles at most one of kwargs because the return is buried in the for loop.
    • timestamp.__repr__ has a single return statement in an else statement. __repr__ always needs to return a string.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Originally Posted by b49P23TIvg
    What is the question? Please present code that does something more than compiles.

    Problems with the program:
    • You've used tabs to indent the code. That's trouble.
    • process handles at most one of kwargs because the return is buried in the for loop.
    • timestamp.__repr__ has a single return statement in an else statement. __repr__ always needs to return a string.
    Yeah, sorry about process, it never got called. I would have caught that straight away if it had. XD thanks.

    As for tabs, I don't mean to sound rude but I don't believe that's a problem and I will continue to code that way regardless of the group consensus regarding "Pythonic" coding. Counting out spaces for every single line of every single code is not worth it. I'm sorry, I respect the institution of common practices, thanks but no thanks.

    I've made those fixes in the code below, but timestamps still won't initialize without arguments.

    Code:
    class glob():
    	show_weekday=True
    	long_forms=False
    
    class timestamp(datetime.datetime):
    	def __repr__(self):
    		pm,hour = divmod((self.hour),12)
    		pm = bool(pm)
    		timestring = (str(hour)+':'+str(self.minute).zfill(2)+':'+str(self.second).zfill(2))
    		if pm:
    			timestring += 'PM'
    		else:
    			timestring += 'AM'
    		datestring = (str(self.month)+'-'+str(self.day)+'-'+str(self.year))
    		if glob.long_forms:
    			wdformat = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
    		else:
    			wdformat = {0:'Mon', 1:'Tue', 2:'Wed', 3:'Thu', 4:'Fri', 5:'Sat', 6:'Sun'}
    		if glob.show_weekday:
    			weekday = wdformat[now.weekday()]
    			return (weekday+','+datestring+','+timestring)
    		else:
    			return datestring+','+timestring
    	def __init__(self,**kwargs):
    		if not kwargs:
    			kwargs = {"year"		: datetime.datetime.now().year,
    				"month"			: datetime.datetime.now().month,
    				"day"			: datetime.datetime.now().day,
    				"hour"            	: datetime.datetime.now().hour,
    				"minute"		: datetime.datetime.now().minute,
    				"second"		: datetime.datetime.now().second,
    				"millis"		: datetime.datetime.now().millisecond}
    		self.__dict__ = process(self.__dict__,kwargs)
    	def process(defargs,kwargs):
    		for kwarg in kwargs:
    			if kwarg in defargs:
    				defargs[kwarg] = kwargs[kwarg]
    			else:
    				raise AttributeError("Invalid keyword: {}".format(kwarg))
    		return defargs
    
    test=timestamp()
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480
    good grief. You'd count spaces for indentation? If I had to do that I'd indent by 1 character not 4. I'd avoid tabs.

    In emacs python major mode C-j (control j) where you'd press your big enter key moves the cursor to the right spot. I'm pretty sure the next person to post will laugh at me because they merely speak to emacs and the entire program is written.

    Anyway, does this program work as you need? Use python3.
    Code:
    import datetime
    
    class glob():
        show_weekday=True
        long_forms=False
    
    class timestamp(datetime.datetime):
    
        def __new__(*args,**kwargs):
            if not kwargs:
                now = datetime.datetime.now()
                kwargs = {
                    "year"   : now.year,
                    "month"  : now.month,
                    "day"    : now.day,
                    "hour"   : now.hour,
                    "minute" : now.minute,
                    "second" : now.second,
                    "microsecond" : now.microsecond,
                    }
    
            return datetime.datetime.__new__(*args,**kwargs)
    
        def __init__(self,*args,**kwargs):
            super().__init__(*args,**kwargs)
    
        def __repr__(self):
            pm,hour = divmod(self.hour,12)
            pm = bool(pm)
            timestring = (str(hour)+':'+str(self.minute).zfill(2)+':'+str(self.second).zfill(2))
            if pm:
                timestring += 'PM'
            else:
                timestring += 'AM'
            datestring = (str(self.month)+'-'+str(self.day)+'-'+str(self.year))
            if glob.long_forms:
                wdformat = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
            else:
                wdformat = {0:'Mon', 1:'Tue', 2:'Wed', 3:'Thu', 4:'Fri', 5:'Sat', 6:'Sun'}
            if glob.show_weekday:
                weekday = wdformat[now.weekday()]
                return (weekday+','+datestring+','+timestring)
            else:
                return datestring+','+timestring
    
    def process(defargs,kwargs):
        for kwarg in kwargs:
            if kwarg in defargs:
                defargs[kwarg] = kwargs[kwarg]
            else:
                raise AttributeError("Invalid keyword: {}".format(kwarg))
        return defargs
    
    test=timestamp()
    print(test)
    Last edited by b49P23TIvg; June 20th, 2013 at 09:29 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Using 3 is not an option for me at the moment, sadly, due to packages that aren't currently supported for it. I would tell you which packages I'm referring to but my memory fails me at the moment. XD

    EDIT/UPDATE: Okay, I caved. Python 3 it is. Thank you.
    Last edited by Mr909; June 23rd, 2013 at 02:52 PM.
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480
    ha ha---had I solved your difficulty in python 2 I'd have presented it. Possibly the same thing with inheritance from object to make a new style class.
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    If you want to use python 2.x and continue to use super (which I always obsessively avoid), this should work.

    python Code:
    def __init__(self,*args,**kwargs):
        super(timestamp,self).__init__(*args,**kwargs)
    Also there shouldn't be anything stopping you from just not using super and doing this instead:
    python Code:
    def __init__(self,*args,**kwargs):
        datetime.datetime.__init__(self,*args,**kwargs)

    -Mek
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Works like a charm!
    Also, I figured out which package for Stackless 3.2 wasn't playing nice: It was pygame.
    I MADE this system to be used in conjunction with two things. One of them was pygame. :P
    So yeah, sorry, back to delightfully simple 2.7 it is. I think I'll leave 3.2 installed, though.
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    There's no reason to do all this convoluted formatting by hand. datetime objects have a strftime method to do this for you. This should be nearly equivalent to your repr method:
    Code:
    def __repr__(self):
        fmt_string = "%m-%d-%Y,%I:%M:%S%p"
        if glob.show_weekday:
            if glob.long_forms:
                fmt_string = "%A," + fmt_string
            else:
                fmt_string = "%a," + fmt_string
        return self.strftime(fmt_string)
    Last edited by Nyktos; June 25th, 2013 at 11:23 PM.

IMN logo majestic logo threadwatch logo seochat tools logo