-2

i have an dataframe with dates and would like to get the time between the first date and the last date, when i run the code below

df.sort_values('timestamp', inplace=True) 
firstDay = df.iloc[0]['timestamp']  
lastDay = df.iloc[len(df)-1]['timestamp']
print(firstDay)
print(lastDay)

it provides the following formate of the dates :

2016-09-24 17:42:27.839496
2017-01-18 10:24:08.629327

and I'm trying to get the different between them but they're in the str format, and I've been having trouble converting them to a form where i can get the difference

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
mike s
  • 23
  • 3
  • 1
    https://stackoverflow.com/questions/466345/converting-string-into-datetime After converting to datetime you can easily find the difference between the two – Dinari Dec 03 '21 at 18:58
  • Before sorting etc, use `df["timestamp"] = pd.to_datetime(df["timestamp"])`. Then you can simply use `df["timestamp"].max() - df["timestamp"].min()` for the difference. – not_speshal Dec 03 '21 at 19:01

1 Answers1

0

here you go :o)

import datetime
from datetime import date
from datetime import datetime
import pandas as pd

date_format_str = '%Y-%m-%d %H:%M:%S.%f'

date_1 = '2016-09-24 17:42:27.839496'
date_2 = '2017-01-18 10:24:08.629327'

start = datetime.strptime(date_1, date_format_str)
end =   datetime.strptime(date_2, date_format_str)

diff = end - start

# Get interval between two timstamps as timedelta object
diff_in_hours = diff.total_seconds() / 3600
print(diff_in_hours)

# get the difference between two dates as timedelta object
diff = end.date() - start.date()
print(diff.days)

Pandas

import datetime
from datetime import date
from datetime import datetime
import pandas as pd

date_1 = '2016-09-24 17:42:27.839496'
date_2 = '2017-01-18 10:24:08.629327'

start = pd.to_datetime(date_1, format='%Y-%m-%d %H:%M:%S.%f')
end = pd.to_datetime(date_2, format='%Y-%m-%d %H:%M:%S.%f')

# get the difference between two datetimes as timedelta object
diff = end - start

print(diff.days)
NeoTheNerd
  • 566
  • 3
  • 11