-2

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

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Jade Han
  • 1,185
  • 5
  • 15
  • 36
  • 2
    Use the [`datetime`](https://docs.python.org/2/library/datetime.html#datetime-objects) module. Specifically, look at `strptime` to first create your `datetime` object. – roganjosh Sep 16 '17 at 08:28

3 Answers3

2

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()
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

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

magicleon94
  • 4,887
  • 2
  • 24
  • 53
0

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.

Zeinab Abbasimazar
  • 9,835
  • 23
  • 82
  • 131