2

i have a pandas dataframe df:

id    value     mins
1      a         12.4
2      u         14.2
3      i         16.2
3      g         17.0

i have a datetime.datetime variable:

current_time = datetime.datetime(2018, 1, 2, 14, 0, 34, 628481)

i want to add new column in my df 'total_time' such that for every row it add the delta value mins in current_time.

id    value     mins        total_time
1      a         12.4   current_time+timedelta(minutes = 12.4)
2      u         14.2            and
3      i         16.2            so
3      g         17.0            on... for every row

i tried:

df['total_time' = current_time+timedelta(minutes = df['mins'].item())

but i got an error:

can only convert an array of size 1 to a Python scalar

Is there any other way of doing this?

i'm using datetime.datetime package

Shubham R
  • 7,382
  • 18
  • 53
  • 119

1 Answers1

2

I think you need to_timedelta with T for minutes:

df['total_time'] = current_time + pd.to_timedelta(df['mins'], unit='T')
print (df)
   id value  mins                 total_time
0   1     a  12.4 2018-01-02 14:12:58.628481
1   2     u  14.2 2018-01-02 14:14:46.628481
2   3     i  16.2 2018-01-02 14:16:46.628481
3   3     g  17.0 2018-01-02 14:17:34.628481

Detail:

print (pd.to_timedelta(df['mins'], unit='T'))
0   00:12:24
1   00:14:12
2   00:16:12
3   00:17:00
Name: mins, dtype: timedelta64[ns]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Wow! nice! also if i had to add one more column as `timestamp`, can i do it by this - ` df['timestamp'] = int(datetime.timestamp(df['total_time'])) ` ? – Shubham R Jan 02 '18 at 06:44
  • I tried using this: ` df['timestamp'] = int(datetime.timestamp(pd.to_datetime(df['total_time']))) ` but got error: `descriptor 'timestamp' requires a 'datetime.datetime' object but received a 'Series'` – Shubham R Jan 02 '18 at 06:47
  • Not sure if understand, what is new column? It is datetimes? Can you explain more? Or need something like `20180102141258628481` ? – jezrael Jan 02 '18 at 06:48
  • Do you need create integers from datetimes? – jezrael Jan 02 '18 at 06:50
  • ok leave that, i see an issue : the datatype of my `current_time = datetime.datetime`, but type of the total_time in my` df = pandas.tslib.Timestamp` Can't i maintain same datatype as datetime.datetime? – Shubham R Jan 02 '18 at 06:52
  • current_time+timedelta(minutes = float_value) returns datetime.datetime object only – Shubham R Jan 02 '18 at 06:53
  • It is not so easy, because in pandas by default are timestamp. By I try find some solution. – jezrael Jan 02 '18 at 06:57
  • its okay, its that's tough, i'll try to even work with this :) – Shubham R Jan 02 '18 at 06:59
  • There is posible use `df['total_time'].dt.to_pydatetime()` from [there](https://stackoverflow.com/a/22825954/2901002), but if assign to new column there are datetimes again. – jezrael Jan 02 '18 at 07:00
  • this to_pydatetime() is also very helpful! – Shubham R Jan 02 '18 at 07:03