luka
luka

Reputation: 529

Timedelta calculation on Dataframe column condition

I have this kind of Dataframe

    Datetime            HomeTeam        AwayTeam    HG  AG  FT  
0   2021-06-05 21:30:00 Palestino   U. De Chile                                                                 
1   2021-06-05 17:00:00 Cobresal    Union La Calera                                                                     
2   2021-06-01 02:30:00 A. Italiano U. De Chile                                                         
3   2021-06-01 00:00:00 Union       Nublense                                                                
4   2021-05-31 21:30:00 Antofagasta Huachipato                                                              
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 
68  2021-03-28 01:00:00 U. Espanola S. Wanderers    3   1   H                                   
69  2021-03-27 22:30:00 Colo Colo   Union La Calera 0   0   D

I want to calculate the datetime different between "Datetime" column and today if "FT" column is blank

Code:

today = datetime.today()
if [df['FT'] == ''] == True:
    for date_ in dates_:
        delta = date_ - today
        if delta.days < -1:
            print(date_)

OUTPUT


date_
NaT

Upvotes: 0

Views: 154

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24304

Firstly convert your Datetime column into datetime[ns] dtype by using to_datetime() method(If it's already in datetime dtype then ignore/skip this step):

df['Datetime']=pd.to_datetime(df['Datetime'])

You can use boolean masking:

mask=df['FT'].isin([float('NaN'),' ',None,'  ',''])

Now get today's date:

today=pd.Timestamp('now')
today=pd.DateOffset(days=today.day,hours=today.hour,minutes=today.minute,seconds=today.second)

Finally pass that mask:

df.loc[mask,'FT']=df.loc[mask,'Datetime']-today

Upvotes: 1

Related Questions