Home > other >  removing days from datetime type python
removing days from datetime type python

Time:08-18

i have a column in my data frame that is date time type. i have it in this format

0         0 days 00:04:12
1         0 days 00:06:54
2         0 days 00:04:57
3         0 days 00:09:48
4         0 days 00:04:50
               ...       
11839     0 days 00:06:39
11840     0 days 00:32:03
11841     0 days 00:02:32
11842   -1 days  00:16:52
11843     0 days 00:09:05

i want to keep the time stamp only. how can i do that

I tried to convert it to string then using substring as followed:

dftime['duration']=dftime['duration'].astype(str)
print(dftime['duration'].str[10:])

but because some values are like "11842 -1 days 00:16:52" . the out but does not come out right . any ideas?

CodePudding user response:

Assuming you want strings as output, you can clip, convert to string and slice:

df['result'] = df['col'].clip('0').astype(str).str[-8:]

output:

                    col    result
0       0 days 00:04:12  00:04:12
1       0 days 00:06:54  00:06:54
2       0 days 00:04:57  00:04:57
3       0 days 00:09:48  00:09:48
4       0 days 00:04:50  00:04:50
11839   0 days 00:06:39  00:06:39
11840   0 days 00:32:03  00:32:03
11841   0 days 00:02:32  00:02:32
11842 -1 days  00:16:52  00:00:00
11843   0 days 00:09:05  00:09:05

Note that any timedelta > 1 day will be incorrect, if you want you can clip to 1 day - 1 second:

df['result'] = df['col'].clip('0', '23h59m59s').astype(str).str[-8:]

example:

                col    result
0   1 days 00:09:05  23:59:59

CodePudding user response:

You can call .time() for each of the entry which will return a data in time type. For example, some_datetime.time().

CodePudding user response:

You can convert it into a string and instead of picking it by character try splitting it up.

dftime['result']=dftime['duration'].astype(str).split()[2]


            duration      result
0       0 days 00:04:12  00:04:12
1       0 days 00:06:54  00:06:54
2       0 days 00:04:57  00:04:57
3       0 days 00:09:48  00:09:48
4       0 days 00:04:50  00:04:50
11839   0 days 00:06:39  00:06:39
11840   0 days 00:32:03  00:32:03
11841   0 days 00:02:32  00:02:32
11842 -1 days  00:16:52  00:00:00
11843   0 days 00:09:05  00:09:05
 

It should split it up on the basis of spaces in between the string so you would have a problem in case the number of days is higher or lower.

  • Related