Domanda

In my database i stored the date time in the following format. I want to get the difference between two samples in seconds. Is it any simple methods are available?

   u'2013-05-20 05:09:06'
   u'2013-05-20 05:10:06'
È stato utile?

Soluzione

Use the datetime module.

>>> import datetime
>>> start = datetime.datetime.strptime(u'2013-05-20 05:09:06', '%Y-%m-%d %H:%M:%S')
>>> end = datetime.datetime.strptime(u'2013-05-20 05:10:06', '%Y-%m-%d %H:%M:%S')
>>> (end - start).total_seconds()
60.0

Altri suggerimenti

For Hours select datediff(hh,'02/02/2013 00:00:00','02/02/2013 01:02:02')

For Minutes select datediff(mi,'02/02/2013 00:00:00','02/02/2013 01:02:02')

For Seconds select datediff(ss,'02/02/2013 00:00:00','02/02/2013 01:02:02')

For Day select datediff(dd,'02/02/2013 00:00:00','02/03/2013 01:02:02')

For Month select datediff(mm,'02/02/2013 00:00:00','03/03/2013 01:02:02')

For year select datediff(yy,'02/02/2013 00:00:00','03/03/2014 01:02:02')

Try this

You can simply subtract two datetime objects and get a datetime.timedelta object, which stores the difference as datetime.timedeleta(days, seconds, microseconds).

So, for example, you could do

>>>difference = second_date - first_date
>>>difference
datetime.timedelta(0, 60)

Seconds can be accessed simply with datetime.timedelta().seconds

>>>difference.seconds
60

If you are using py2.7 then simply use delta.total_seconds()

>>> s = datetime(2013, 05, 20, 5, 9, 6)
>>> t = datetime(2013, 05, 21, 6, 29, 30)
>>> u = t - s
>>> u.seconds
4824
>>> u.total_seconds()
91224.0

but for earlier versions you need to do it by adding time parts separately.

>>> u.seconds + u.days * 86400
91224
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top