Archive

Posts Tagged ‘strptime’

python/sqlite Date

April 10, 2012 Leave a comment

I was doing some work with sqlite3 databases in python and got a few problems with dates.

First problem was with datetime.strptime. I was coding a multi-threaded algorithm and found the hard way that this function isn’t thread safe! And python returned an exception complaining about failing to obtain a lock (mutex).

Fix: Simply execute some command using datetime.strptime *before creating* any thread.

datetime.strptime(“2012-04-10 22:22:22″,”%Y-%m-%d %H:%M:%S”)

Second problem, after fixing the threads issue now python was returning a “ValueError: unconverted data remains:”. This is a simple fix, there was some part of the date string that was being ignored.

Fix: Use this as a format “%Y-%m-%d %H:%M:%S.%f”

For last my sqlite3 now was using a different time from my machine, after a small search found that if you are receiving dates from an external source to the sqlite3 engine you should add the “localtime” to the call.

Example:

  • strftime(‘%s’,’now’,’localtime’) – This returned GMT (my system time)
  • strftime(‘%s’,’now’) – This returned GMT -1 (maybe a default)

I hope this helps someone with the same problem 🙂