Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe equivalent to python's time.strptime()?

Tags:

Something I wrote throws a lot of AttributeError exceptions when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux) but whatever- upon a'Googling, it seems that time.strptime() isn't considered thread-safe.

Is there a better way to create a datetime object from a string? Current code looks like:

val = DateFromTicks(mktime(strptime(val, '%B %d, %Y'))) 

But, that yields the exceptions as it's run inside a thread.

Thanks!

like image 328
Wells Avatar asked Mar 11 '10 17:03

Wells


People also ask

Is Strptime thread safe?

strptime() isn't considered thread-safe. But, that yields the exceptions as it's run inside a thread.

What is Strptime ()?

strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.

How do I use Strftime and Strptime in Python?

Python time strptime() MethodThe format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.


2 Answers

According to the bug report, this doesn't happen if you call strptime once before creating your threads. I've done a little testing which seems to confirm this. So just make any call to strptime during initialization as a workaround.

like image 172
interjay Avatar answered Oct 06 '22 01:10

interjay


Just another workaround for this bug, you can simply import _strptime manually, along with datetime

import _strptime from datetime import datetime  # then, in threaded block datetime.strptime(date, format) 
like image 23
Romuald Brunet Avatar answered Oct 06 '22 00:10

Romuald Brunet