I want subtract string
type time
a = "2017-04-15 21:10:02.026"
b = "2017-10-15 10:09:57.321"
I want a-b
please somebody help me thank you
I want subtract string
type time
a = "2017-04-15 21:10:02.026"
b = "2017-10-15 10:09:57.321"
I want a-b
please somebody help me thank you
You need to convert them first to a datetime
:
from datetime import datetime
a = "2017-04-15 21:10:02.026"
b = "2017-10-15 10:09:57.321"
dt_a = datetime.strptime(a, "%Y-%m-%d %H:%M:%S.%f")
dt_b = datetime.strptime(b, "%Y-%m-%d %H:%M:%S.%f")
print dt_a - dt_b
This will display:
-183 days, 11:00:04.705000
datetime.strptime()
is used to convert the string into a datetime
by specifying how the string is formatted. Each %
tells it where each part of the date/time is.
In your case, the formatting needed is as follows:
%Y
- Year with century as a decimal number.
%m
- Month as a zero-padded decimal number.
%d
- Day of the month as a zero-padded decimal number.
%H
- Hour (24-hour clock) as a zero-padded decimal number.
%M
- Minute as a zero-padded decimal number.
%S
- Second as a zero-padded decimal number.
%f
- Microsecond as a decimal number, zero-padded on the left.
Subtracting two datetime
objects will return you a timedelta
object. With this you can determine the total_seconds()
. e.g.
result = dt_a - dt_b
print result.total_seconds()
According to this you can do this way (see all the options with %
in the linked documentation:
>>> from datetime import datetime
>>> a = "2017-04-15 21:10:02.026"
>>> b = "2017-10-15 10:09:57.321"
>>> oA = datetime.strptime(a,"%Y-%m-%d %H:%M:%S.%f")
>>> oB = datetime.strptime(b,"%Y-%m-%d %H:%M:%S.%f")
>>> oA - oB
>>> datetime.timedelta(-183, 39604, 705000)
According to this timedelta
should be returning (days, seconds, milliseconds)
this way
Use datetime
as following:
import datetime
if __name__ == "__main__":
a = "2017-04-15 21:10:02.026"
b = "2017-10-15 10:09:57.321"
a_time = datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S.%f")
b_time = datetime.datetime.strptime(b, "%Y-%m-%d %H:%M:%S.%f")
print (b_time - a_time).total_seconds()
b_time - a_time
creates a timedelta
object which have multiple attributes which you can find here; total_seconds
returns time difference in seconds.