-4
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?

ismail
  • 41,546
  • 8
  • 79
  • 92
Deepti
  • 1
  • 3
    https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime – jonrsharpe Apr 15 '14 at 09:32
  • 1
    Why don't you use the proper MySQL type for a datetime? See https://dev.mysql.com/doc/refman/5.7/en/datetime.html –  Apr 15 '14 at 09:35

3 Answers3

1

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
Chris Clarke
  • 1,891
  • 1
  • 13
  • 19
  • from datetime import datetime t=str(datetime.now()) print(t) date_object = datetime.strptime("t", "%Y-%m-%d %H:%M:%S") print(date_object) Could you help me with this code? – Deepti Apr 15 '14 at 09:59
0

This falls into two separate tasks:

  • How to parse date from string here.

  • How to use mysql from python here

Community
  • 1
  • 1
aisbaa
  • 7,544
  • 5
  • 28
  • 40
0

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
Nishant Nawarkhede
  • 6,960
  • 9
  • 49
  • 67