I have a string time that's in %H:%M:%S %b %d %Y
format. What is the best way I can compare current time with that given time and get the difference in minutes? I'm thinking parse each part in the string and compare with the parsed string of current time. There has to be a better way than this
Asked
Active
Viewed 72 times
-4

Csfcodejs
- 3
- 1
- 4
-
Can you provide your code? – Alan Kavanagh Feb 11 '19 at 22:47
-
2parse the string with `datetime.strptime`. – Daniel Feb 11 '19 at 22:49
-
turn the string into a `datetime` object and then use the `timedelta` object to compare. `https://docs.python.org/3/library/datetime.html` – mmenschig Feb 11 '19 at 22:56
2 Answers
1
You're right, there's certainly an easier way. You may want to try this approach:
- Convert the given string into a
datetime
object. Click here for info on Python's datetime module. See also this answer. - Generate the current time as another
datetime
object. - Get the time difference between the two. This is just a matter of subtracting one from the other. See this answer for an example.
- Convert this to minutes. This is a little trickier. If your two times are
a
andb
, thenc = a-b
gives you a new datetime object representing the difference. You can take the valuesc.days
,c.seconds
andc.microseconds
, then mathematically convert each of the values to minutes, and add them all up.

Bill M.
- 1,388
- 1
- 8
- 16