5

I have two date strings (taken from user input and can vary greatly)

s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'

I wish to find the difference between the two as minutes.

How should I proceed to tackle this ?

Simply Seth
  • 3,246
  • 17
  • 51
  • 77
  • http://stackoverflow.com/questions/6788807/add-timestamps-in-python-month-wise This would help u resolve the issue – Rajeev Sep 29 '11 at 18:36
  • A quick Google search dug up this library: http://www.egenix.com/products/python/mxBase/mxDateTime/ - It seems to have the ability to process arbitrary formats, which you mentioned might be a requirement for you. I think the standard datetime libraries you have to specify an exact format to parse. – Mike Christensen Sep 29 '11 at 18:54

4 Answers4

9
import datetime

d1 = datetime.datetime.strptime('2011:10:01:10:30:00', '%Y:%m:%d:%H:%M:%S')
d2 = datetime.datetime.strptime('2011:10:01:11:15:00', '%Y:%m:%d:%H:%M:%S')
diff = (d2 - d1).total_seconds() / 60

If you need to handle arbitrary datetime formats, I don't believe the built in datetime library will do that for you. Perhaps check out something like:

http://www.egenix.com/products/python/mxBase/mxDateTime/

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
5

Using the datetime module, parse into a datetime object using strptime, then subtract. You'll get a timedelta. Then use timedelta.total_seconds() and divide by 60.

agf
  • 171,228
  • 44
  • 289
  • 238
nmichaels
  • 49,466
  • 12
  • 107
  • 135
4

Use datetime to parse the string and convert into a base epoch time. Do the math. Convert back:

>>> from datetime import datetime
>>> s1 = '2011:10:01:10:30:00'
>>> s2 = '2011:10:01:11:15:00'
>>> d1=datetime.strptime(s1,'%Y:%m:%d:%I:%M:%S')
>>> d2=datetime.strptime(s2,'%Y:%m:%d:%I:%M:%S')
>>> d2-d1
datetime.timedelta(0, 2700)
>>> (d2-d1).total_seconds()/60
45.0

If you are looking for arbitrary date string parsing, check out DateUtil and the parse function.

the wolf
  • 34,510
  • 13
  • 53
  • 71
1

The time module can be helpful for this.

import time

s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'

s1Time = time.strptime(s1, "%Y:%m:%d:%H:%M:%S")
s2Time = time.strptime(s2, "%Y:%m:%d:%H:%M:%S")

deltaInMinutes = (time.mktime(s2Time) - time.mktime(s1Time)) / 60.0
print deltaInMinutes, "minutes"
Nate
  • 18,892
  • 27
  • 70
  • 93