0

Python code help needed: I have datetime difference of created and closed date in this format - 01/30/2020 1:55:00 and 01/30/2020 09:44:00. Need to convert the above date format difference to total seconds. How can I do sometime the difference will be in days and time like - 25 days, 05:23:00. How to convert the above format of time difference between two dates to total seconds and store it back in the same dataframe as a new column.

Any help provided will be really appreciated.

  • 1
    Does this answer your question? [How do I check the difference, in seconds, between two dates?](https://stackoverflow.com/questions/4362491/how-do-i-check-the-difference-in-seconds-between-two-dates) – divibisan Jul 09 '20 at 00:39

3 Answers3

0

This code might help you.

import datetime

date1 = "01/30/2020 1:55:00"
date2 = "01/30/2020 09:44:00"

date1_obj = datetime.datetime.strptime(date1, '%m/%d/%Y %H:%M:%S')
date2_obj = datetime.datetime.strptime(date2, '%m/%d/%Y %H:%M:%S')

difference_seconds = abs((date1_obj - date2_obj).seconds)
difference_days = abs((date1_obj - date2_obj).days)
print (difference_seconds)
print (difference_days)
fro
  • 402
  • 3
  • 8
0

A datetime object has a method called timestamp() that returns the number of seconds since the start of 1970. Just do it for both datetimes and subtract.

seconds = date1.timestamp() - date2.timestamp()
Andrew Allaire
  • 1,162
  • 1
  • 11
  • 19
0

If you're using a pandas dataframe then you can use the series dt accessor to convert the difference between dates to seconds.

import pandas as pd

df = pd.DataFrame(data={
    'from': ["01/30/2020 1:55:00", "01/25/2020 15:30:00"],
    'to': ["01/30/2020 09:44:00", "01/26/2020 1:55:00"]})

# convert to datetime objects
df['from'] = pd.to_datetime(df['from'])
df['to'] = pd.to_datetime(df['to'])

df['difference'] = (df['to'] - df['from'])

df['difference_seconds'] = df['difference'].dt.total_seconds()

print(df)

This will give a table like:

|    | from                | to                  | difference      |   difference_seconds |
|---:|:--------------------|:--------------------|:----------------|---------------------:|
|  0 | 2020-01-30 01:55:00 | 2020-01-30 09:44:00 | 0 days 07:49:00 |                28140 |
|  1 | 2020-01-25 15:30:00 | 2020-01-26 01:55:00 | 0 days 10:25:00 |                37500 |
richardjmorton
  • 311
  • 2
  • 7