Home > Code, Tutorial > python/sqlite Date

python/sqlite Date

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 🙂

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: