0

I have DateTime, from string I convert them on IS0 format example. ISODate("2016-06-24T09:07:31.097Z")

I want to find the differences between them using python, so I did this:

string_older = "2016-05-18T20:53:43.776456"
string_young = "2016-05-16T20:53:43.776456"
datetime_older = datetime.datetime.strptime(string_older, "%Y-%m-%dT%H:%M:%S.%f") //date on ISO format
datetime_young = datetime.datetime.strptime(string_young, "%Y-%m-%dT%H:%M:%S.%f") //date on ISO format
a = time.mktime(datetime_older)
b = time.mktime(datetime_young)
diff = a - b
seconds = int(diff) % 60

But this gives this error TypeError: argument must be 9-item sequence, not datetime.datetime at this line time.mktime(datetime_older). I don't know how to fix it? Please help.

2
  • I don't understand why you are calling time.mktime at all. You have datetimes already, you can subtract them from each other. Commented Jun 29, 2016 at 12:52
  • I thought to convert it to time and then subtract for find difference on seconds, I didn't know that I can subtract dates directly Commented Jun 29, 2016 at 12:54

2 Answers 2

3

Subtracting both datetimes gives you a timedelta. To get the difference expressed in seconds, call its total_seconds method.

string_older = "2016-05-18T20:53:43.776456"
string_young = "2016-05-16T20:53:43.776456"
datetime_older = datetime.datetime.strptime(string_older, "%Y-%m-%dT%H:%M:%S.%f") //date on ISO format
datetime_young = datetime.datetime.strptime(string_young, "%Y-%m-%dT%H:%M:%S.%f")

timedelta = datetime_older - datetime_young
seconds = timedelta.total_seconds()

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.

Sign up to request clarification or add additional context in comments.

Comments

0

I think you need this; there is no need to use time.mktime() as you already have datetimes.

import time, datetime
string_older = "2016-05-18T20:53:43.776456"
string_young = "2016-05-16T20:53:43.776456"

datetime_older = datetime.datetime.strptime(string_older, "%Y-%m-  %dT%H:%M:%S.%f")
datetime_young = datetime.datetime.strptime(string_young, "%Y-%m-%dT%H:%M:%S.%f")

c = datetime_older - datetime_young
print(divmod(c.days * 86400 + c.seconds, 60) ) # minutes, seconds

2 Comments

Why not use total_seconds? (See my answer)
we can use total_seconds. This is just an another way of doing the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.