Datetime.strptime - NonType error on second use
#16
(2016-09-16, 23:27)zbyna Wrote:
(2016-07-02, 21:29)tmelin Wrote: I also bumped into this on a Jarvis platform just now. Workaround that also worked for me:


Code:
Code:
try:
    datetime.strptime(date_string, format)
except TypeError:
    datetime(*(time.strptime(date_string, format)[0:6]))

The same problem. Can confirm workaround. Laugh
Big thanks !!!

Now I bumped into this on a Krypton platform, workaround worked perfectly, thank you!!
Reply
#17
Below is an alternative approach to solve the problem, if you can not modify the file that has datetime.strptime is used.

It simply overwrites the datetime.strptime method in namespace, so you dont have to modify the source file where datetime.strptime is used.

PHP Code:
import datetime
import time

#fix for datatetime.strptime returns None
class proxydt(datetime.datetime):
    
def __init__(self, *args, **kwargs):
        
super(proxydtself).__init__(*args, **kwargs)

    @
staticmethod
    def strptime
(date_stringformat):
        return 
datetime.datetime(*(time.strptime(date_stringformat)[0:6]))

datetime.datetime proxydt 
Reply
#18
Last example didn't work for, this one works:
python:

import datetime
import time

#fix for datatetime.strptime returns None
class proxydt(datetime.datetime):
    def __init__(self, *args, **kwargs):
        super(proxydt, self).__init__(*args, **kwargs)

    @classmethod
    def strptime(cls, date_string, format):
        return datetime(*(time.strptime(date_string, format)[0:6]))

datetime.datetime = proxydt
from datetime import datetime
P.S. Now - 2019, topic was started in 2011. Hmm.... Awesome
Reply
#19
Absolutely insanity that this bug is not fixed in python yet and one needs to override this like the suggested work-around (which works, so thanks). I just spend one hour going crazy looking for typo's and other ghosts in my code.
Reply
#20
(2019-10-07, 08:44)FreakMurderer Wrote: Last example didn't work for, this one works:
python:

import datetime
import time

#fix for datatetime.strptime returns None
class proxydt(datetime.datetime):
    def __init__(self, *args, **kwargs):
        super(proxydt, self).__init__(*args, **kwargs)

    @classmethod
    def strptime(cls, date_string, format):
        return datetime(*(time.strptime(date_string, format)[0:6]))

datetime.datetime = proxydt
from datetime import datetime
P.S. Now - 2019, topic was started in 2011. Hmm.... Awesome

thanks for this. I'm migrating my add-on to Python 3 and with above code I got the following error:
Quote:TypeError: object.__init__() takes no arguments

I had to change it to
python:

import datetime
from sys import version_info

class proxydt(datetime.datetime):
    def __init__(self, *args, **kwargs):
        if version_info < (3,):
            super(proxydt, self).__init__(*args, **kwargs)

    def __new__(cls, *args, **kwargs):
        return super(proxydt, cls).__new__(cls, *args, **kwargs)

    @classmethod
    def strptime(cls, date_string, format):
        import time
        return datetime(*(time.strptime(date_string, format)[0:6]))

datetime.datetime = proxydt
from datetime import datetime
But I have not tested this with Python 2 yet so no guarantees...
Always read the online manual (wiki), FAQ (wiki) and search the forum before posting.
Do not e-mail Team Kodi members directly asking for support. Read/follow the forum rules (wiki).
Please read the pages on troubleshooting (wiki) and bug reporting (wiki) before reporting issues.
Reply
#21
I had written that workaround several years ago and i dont remember why i used @classmethod. Instead @staticmethod would be much way cleaner. And there is no need to override __init__ method as well.

EDIT: I have used staticmethod in the first place ok, but still overriding __init__ was unnecessary. Super has variance between py2 and py3, this will also eliminate the py3 issues.

python:

import datetime

#fix for datatetime.strptime returns None
class proxydt(datetime.datetime):
@staticmethod
def strptime(date_string, format):
import time
return datetime.datetime(*(time.strptime(date_string, format)[0:6]))

datetime.datetime = proxydt

Reply
#22
I greet a newcomer to Python, so I'll try to make a simple context menu for myself. And I came across this error, but I don't know how to implement the fix in my code. Can anyone advise me please?

the addon only works once and then discards the error mentioned here.

Code:
​​​​​​​import xbmc
import xbmcgui
import time
from datetime import datetime, timedelta

title = xbmc.getInfoLabel('Listitem.Title')
olddate = xbmc.getInfoLabel('Listitem.Date')
start = xbmc.getInfoLabel('Listitem.StartTime')
name = xbmc.getInfoLabel('ListItem.ChannelName')
url = '/ADRESA'
get = '_'
newdate = datetime.strptime(olddate, "%d.%m.%Y %H:%M") + (timedelta(hours=-2))

file = 'ADRESA' + newdate.strftime("%Y%m%d") + get + name.replace(" ", "_") + get + newdate.strftime("%Y%m%d_%H%M%S") + url

xbmc.Player().play(file)
Reply
#23
Well remove that from datetime import datetime from your code and put boogiepops code underneath your imports. that should fix it.
Reply
#24
Not work.. error log

Code:
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
                                             - NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
                                            Error Type: <type 'exceptions.AttributeError'>
                                            Error Contents: 'module' object has no attribute 'strftime'
                                            Traceback (most recent call last):
                                              File "/Users/lukasmraz/Library/Application Support/Kodi/addons/context.pvr.backtvgo/addon.py", line 20, in <module>
                                                newdate = datetime.strftime(olddate, "%d.%m.%Y %H:%M") + (timedelta(hours=-2))
                                            AttributeError: 'module' object has no attribute 'strftime'
                                            -->End of Python script error report<--

Code:
import xbmc
import xbmcgui
import datetime

#fix for datatetime.strptime returns None
class proxydt(datetime.datetime):
    @staticmethod
    def strptime(date_string, format):
        import time
        return datetime.datetime(*(time.strptime(date_string, format)[0:6]))

datetime.datetime = proxydt

title = xbmc.getInfoLabel('Listitem.Title')
olddate = xbmc.getInfoLabel('Listitem.Date')
start = xbmc.getInfoLabel('Listitem.StartTime')
name = xbmc.getInfoLabel('ListItem.ChannelName')
url = 'ADRESA'
get = '_'
newdate = datetime.strptime(olddate, "%d.%m.%Y %H:%M") + (timedelta(hours=-2))

file = 'ADRESA' + newdate.strftime("%Y%m%d") + get + name.replace(" ", "_") + get + newdate.strftime("%Y%m%d_%H%M%S") + url

xbmc.Player().play(file)
Reply
#25
Sorry if I'm being a complete noob here (I generally don't touch python) but I've mostly seen it qualified as datetime.datetime.strptime()
Reply
#26
yes it works. but now again "timedelta" doesn't work when deleting "from datetime import datetime, timedelta"
Reply
#27
(2020-05-29, 13:03)djlucas456 Wrote: yes it works. but now again "timedelta" doesn't work when deleting "from datetime import datetime, timedelta"

Can't you just qualify it the same way: datetime.timedelta? Sorry, I generally get lost with python's import statements...
Reply
#28
fix.. work me.. (timedelta(hours=-2) > (datetime.timedelta(hours=-2)

thanks
Reply
#29
(2012-10-15, 17:43)Leopold Wrote: Thanks, this works, but I ended up taking a simpler example from the Python doc.
 
Code:
try:
    datetime.strptime(date_string, format)
except TypeError:
    datetime(*(time.strptime(date_string, format)[0:6]))

I ran into this issue (type error on second iteration of strptime) over the weekend porting an addon to Matrix and adding some new functionality.   The workaround above worked perfectly. 


Thanks,

Jeff
Running with the Mezzmo Kodi addon.  The easier way to share your media with multiple Kodi clients.
Service.autostop , CBC Sports, Kodi Selective Cleaner and Mezzmo Kodi addon author.
Reply
#30
As already mentioned, this is a known problem to embedded python, which Kodi uses. There is not sufficient interest in donors to Python development to fix the problem.The problem is worse than you think:
  1. I have seen Kodi crash due to this.
  2. As I understand it, the root problem is that the _strptime module is loaded once in the lifetime of a process which Python runs, but when the interpreter is reinitialized (say, to run another addon, or on re-launch of addon) then this module is corrupted / not properly reinitialized. There is not a simple fix for this in the runtime.
  3. Since addons don't run in a vacuum, other code that does not account for this can break your addon or crash Kodi.
  4. The time.strptime workaround is good, but not perfect. time.strptime does not support sub-second times and can throw exceptions on format strings that it does not understand (although we don't hear a lot of complaints about this, but, who really needs microsecond accuracy in everyday usage).
  5. I think that a combination Monkey Patch and calling a substitute function is best. The Monkey Patch is global to the embedded sub-process (each addon runs in it's own subprocess). The Monkey patch will protect you from other code that hits this problem. Having code call a substitute function (my_striptime) is better documented. Actually the Monkey patch should simply use my_striptime.
I'm implementing a Monkey patch for several addons that I am working on. I'll share when I'm happy with it. I would like to bullet proof it a bit against format strings that it doesn't understand. email.utils.parsedate_tz might be useful for when the format string is not understood. It appears that parsedate_tz does not depend upon datetime.strptime.

As mentioned in an earlier post, the official bug is: https://bugs.python.org/issue27400
Reply

Logout Mark Read Team Forum Stats Members Help
Datetime.strptime - NonType error on second use1