0

I have two string inputs and I need to compare if their difference is 15 min

input1: 20-25-43 (string, represent HH-MM-SS) input2: 20-40-43(string, represent HH-MM-SS)

Initially, I was thinking to replace hyphen(-) and convert string to number and input2 - input1. However, the result is either 1500 or 5500.

I am wondering if there is possible to use the time() method of DateTime objects?

alift
  • 1,855
  • 2
  • 13
  • 28
Nunu
  • 15
  • 2
  • 4
    What does this have to do with `bucket` or `amazon-s3`? – Scott Hunter Feb 10 '20 at 23:44
  • 4
    Does this answer your question? [Comparing two date strings in Python](https://stackoverflow.com/questions/20365854/comparing-two-date-strings-in-python) – alift Feb 10 '20 at 23:48
  • You could use the base package time methods to do this, but it's probably overkill. Converting string to numbers and subtracting is fine, but remember there are 60 seconds per minute and 60 minutes per hour. – Hymns For Disco Feb 10 '20 at 23:50
  • @ScottHunter it is s3 key, key naming convention including id-date1-time1-date2-time2.extension – Nunu Feb 11 '20 at 16:48
  • @alift Yes, it does!! thank you so much – Nunu Feb 11 '20 at 16:49

2 Answers2

4

You can use datetime.strptime to parse them.

>>> from datetime import datetime
>>> s1 = datetime.strptime('20-25-43','%H-%M-%S')
>>> s2 = datetime.strptime('20-40-43','%H-%M-%S')
>>> (s2-s1).seconds
900
abc
  • 11,579
  • 2
  • 26
  • 51
1

Using datetime.strptime you can calculate differences between times. Since you're using a string you need to use strptime to convert it into a datetime object.

string1 = '20-25-43'
string2 = '20-40-42'
FRMAT = '%H-%M-%S'

str(datetime.strptime(string2, FRMAT) - datetime.strptime(string1, FRMAT))


#'0:15:00'

You can then check that your result is == to 15 minutes.

PacketLoss
  • 5,561
  • 1
  • 9
  • 27