0

I currently have two columns within my dataframe in the following format:

Col1 = 2020-12-04T20:16:26+00:00

Col2 = 2020-12-04T20:58:14+00:00

I just want to create a new column that is the time difference between these two values. I've tried the following but encounter an error:

df['Subtract_time'] = df['Col1'] - df['Col2']

Error: unsupported operand type(s) for -: 'str' and 'str'

Additionally, how would I utilize .strptime() to extract just the date from the timestamp. I've tried the following to no avail.....is there any type of guide to understand what combination of '%Y/%m/%d/%h/%M/%S' for any given timestamp?

date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
  • You're trying to subtract two 'str' type columns but should convert them to `datetime` dtype before performing your calculations. See [here](https://stackoverflow.com/questions/37583870/difference-between-two-dates-in-pandas-dataframe). Also read [this](https://www.programiz.com/python-programming/datetime/strptime#format-codes) `strptime()` code list, it should help format your timestamp. – Ava Barbilla Dec 05 '20 at 20:18
  • Does this answer your question? [How to convert string to datetime format in pandas python?](https://stackoverflow.com/questions/32204631/how-to-convert-string-to-datetime-format-in-pandas-python) – FObersteiner Dec 05 '20 at 20:42

1 Answers1

0

Are your columns formatted correctly?

Furthermore you can try this to subtract those timestamps:

df['Subtract_time'] = (df.Col1 - df.Col2)

Another method would be:

df['Subtract_time'] = df.Col1.sub(df.Col2)
Lukas Scholz
  • 622
  • 5
  • 11