from datetime import datetime
t=str(datetime.now())
I store this time in a mysql table in varchar format. Now I want to retrieve this time from mysql table and subtract it from the current time. How do I do it?
from datetime import datetime
t=str(datetime.now())
I store this time in a mysql table in varchar format. Now I want to retrieve this time from mysql table and subtract it from the current time. How do I do it?
That depends, you're storing it as a varchar, so presumably you need to get it back into a datetime? (something like sqlalchemy would do this for you)
You can use datetime.strptime to convert your string (varchar) back to a datetime object.
Then
datetime.now() - retrieved_time
will give you a datetime.timedelta object
edit: help as requested
>>> from datetime import datetime
>>> t = datetime.now()
>>> print t
2014-04-16 08:33:22.309991
that's the format you should be storing in your db
>>> stored_t = datetime.strptime('2014-04-10 08:32:00.934079', "%Y-%m-%d %H:%M:%S.%f") # You should be getting this from your db
>>> print stored_t
2014-04-10 08:32:00.934079
>>> td = t - stored_t
>>> print td
6 days, 0:01:21.375912
Try this , Here is demo
>>> from datetime import datetime
>>> now=datetime.now()
>>> d1='2014-4-14' #get this from database.
>>> d1 = datetime.strptime(d1, "%Y-%m-%d")
>>> (now-d1).days
Output:
1