How to remove last 5 characters from a string in pandas series

Viewed 2865

Trying to remove "time" from rows in column using pandas '06/07/2020 14:00' How can I access last 6 characters of a string to replace it using str.replace("x", "") Your advice will be much appreciated.

4 Answers
data = {'datetime': ['06/07/2020 14:00', '06/07/2020 16:00', '06/07/2020 18:00']}
df = pd.DataFrame(data)

df['date'] = df['datetime'].str[:-6]
.str[:-5] 

is the solution I was looking for.

time_and_date = '06/07/2020 14:00'
only_time = time_and_date.split(' ')[1]
# or
only_time = time_and_date[-5:]

if you want to replace the time in the string, you can do it like this:

time_and_date = '06/07/2020 14:00'
new_value_to_be_placed = 'Some value'
new_time_and_date = time_and_date.split(' ')[0] + new_value_to_be_placed

Use apply and lambda expressions. If your column is really a string:

import pandas as pd
from datetime import datetime, timedelta
d1 = {'my_date_str': ['06/07/2020 14:00', '08/07/2020 14:00'], 'my_date': [datetime.now(), datetime.now() - timedelta(days=10)]}
d1 = pd.DataFrame(data=d1)

d1['my_date_str_new'] = d1['my_date_str'].apply(lambda x: x[:10])

if your column is a datetime object:

d1['my_date_new'] = d1['my_date'].apply(lambda x: x.date())
Related