24

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!

Michel
  • 691
  • 3
  • 19
Wells
  • 9,693
  • 10
  • 50
  • 77

4 Answers4

28

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.

interjay
  • 101,717
  • 21
  • 254
  • 248
19

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)
Romuald Brunet
  • 5,140
  • 3
  • 35
  • 33
0

Have you tried manually synchronizing it yourself? Possibly using the synchronization decorator from this recipe.

Hank Gay
  • 67,855
  • 33
  • 155
  • 219
-3

When I use import datetime the datetime.datetime.strptime() does not throw the exception anymore.

Ηλίας
  • 2,480
  • 4
  • 30
  • 44