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
  • 769
  • 4
  • 19
Wells
  • 10,415
  • 14
  • 55
  • 85

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
  • 107,303
  • 21
  • 270
  • 254
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,595
  • 4
  • 38
  • 34
0

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

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
-3

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

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