Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn a string back into a datetime timedelta

A column in my pandas data frame represents a time delta that I calculated with datetime then exported into a csv and read back into a pandas data frame. Now the column's dtype is object whereas I want it to be a timedelta so I can perform a groupby function on the dataframe. Below is what the strings look like. Thanks!

  0 days 00:00:57.416000
  0 days 00:00:12.036000
  0 days 16:46:23.127000  
 49 days 00:09:30.813000  
 50 days 00:39:31.306000  
 55 days 12:39:32.269000
-1 days +22:03:05.256000

Update, my best attempt at writing a for-loop to iterate over a specific column in my pandas dataframe:

def delta(i):
    days, timestamp = i.split(" days ")
    timestamp = timestamp[:len(timestamp)-7]
    t = datetime.datetime.strptime(timestamp,"%H:%M:%S") + 
    datetime.timedelta(days=int(days))
    delta = datetime.timedelta(days=t.day, hours=t.hour, 
    minutes=t.minute, seconds=t.second)
    delta.total_seconds()

data['diff'].map(delta)
like image 841
Graham Streich Avatar asked Jun 18 '17 03:06

Graham Streich


2 Answers

Use pd.to_timedelta

pd.to_timedelta(df.iloc[:, 0])

0     0 days 00:00:57.416000
1     0 days 00:00:12.036000
2     0 days 16:46:23.127000
3    49 days 00:09:30.813000
4    50 days 00:39:31.306000
5    55 days 12:39:32.269000
6   -1 days +22:03:05.256000
Name: 0, dtype: timedelta64[ns]
like image 195
piRSquared Avatar answered Sep 21 '22 09:09

piRSquared


import datetime

#Parse your string
days, timestamp = "55 days 12:39:32.269000".split(" days ")
timestamp = timestamp[:len(timestamp)-7]

#Generate datetime object
t = datetime.datetime.strptime(timestamp,"%H:%M:%S") + datetime.timedelta(days=int(days))

#Generate a timedelta
delta = datetime.timedelta(days=t.day, hours=t.hour, minutes=t.minute, seconds=t.second)

#Represent in Seconds
delta.total_seconds()
like image 22
user1767754 Avatar answered Sep 22 '22 09:09

user1767754