Nam Ngo's blog

Musings of a Software Developer.

Python Strptime Is Not Thread-safe

When using Python to automate your work, threading is one thing you need to know of. I’ve got into a problem with threading when parsing time. To be exact: datetime.datetime.strptime() function was not thread-safe. Luckily, I found a solution on StackOverflow.

This is how the problem occurred:

1
2
3
4
5
6
7
8
9
from datetime import datetime
import threading

def parse_time(value):
    # Parse time with strptime()
    datetime.strptime(value], "%Y-%m-%d %H:%M:%S.%f")

t = threading.Thread(target=parse_time, args=(value))
t.start()

Fixing it was pretty straightforward. Just make a dummy call on strptime() before creating a thread:

1
2
3
datetime.strptime("2011-04-05 18:40:58.525996", "%Y-%m-%d %H:%M:%S.%f")
t = threading.Thread(target=format_time, args=(some_values))
t.start()

Comments