Home > OS >  How can I split dict based on what the key ends with
How can I split dict based on what the key ends with

Time:09-26

I'm trying to split this data_dict

 Timestamp('2022-09-18 06:00:00'): [5.4, 6.0, 6.5, 6.7, 6.9, 7.9, 8.5,7.5, 7.9, 7.8, 7.6, 6.8],
 Timestamp('2022-09-18 18:00:00'): [6.4, 5.7, 4.8, 5.4, 4.7, 4.3],
 Timestamp('2022-09-19 06:00:00'): [3.8],
 Timestamp('2022-09-19 00:00:00'): [4.1, 4.4, 4.3, 3.8, 3.5, 2.8]}

I'm trying to split it into 2 different dicts based on if the key ends with 06:00:00 or not, i wrote the following code:

def split_morning_night(data_dict):
    mornings = {}
    nights = {} 
    for date, value in data_dict.items():
        if date.endswith("06:00:00"):
            mornings[date] = value
        else:
            nights[date] = value
    return mornings, nights

But im getting the following error when running

AttributeError: 'Timestamp' object has no attribute 'endswith'

Is there any other way to solve this problem? All help appreciated

CodePudding user response:

You are using string method with Timestamp in your split_morning_night() method. First typecast it then use it, something like this.

if str(date).endswith("06:00:00"):
    mornings[date] = value
else:
    nights[date] = value
  • Related