1

Given a CSV data frame that contains two columns "Start date" and "End date"

Start date          End date
10/1/2017 15:23:25  10/1/2017 15:26:26
10/1/2017 15:42:57  10/1/2017 17:49:59

How do I convert this to a list with a two entry dictionary like this:

[{'start': datetime.datetime(2017, 10, 1, 15, 23, 25),
  'end': datetime.datetime(2017, 10, 1, 15, 26, 26)},
 {'start': datetime.datetime(2017, 10, 1, 15, 42, 57),
  'end': datetime.datetime(2017, 10, 1, 17, 49, 59)}]

I'm close but not quite there:

import pandas as pd

# Create a Pandas DataFrame
df = pd.DataFrame({'Start Date': ['10/1/2017 15:23:25', '10/1/2017 15:42:57'],
               'End Date': ['10/1/2017 15:26:26', '10/1/2017 17:49:59']})

# Create a list of dictionaries
list_of_dicts = []

# Loop over the DataFrame rows
for index, row in df.iterrows():

# Create a dictionary
dict_ = {'start': pd.to_datetime(row['Start Date']), 
'end': pd.to_datetime(row['End Date'])}

# Append the dictionary to the list
list_of_dicts.append(dict_)

# Print the list of dictionaries
print(list_of_dicts)

Which gives me:

[{'start': Timestamp('2017-10-01 15:23:25'), 
'end': Timestamp('2017-10-01 15:26:26')}, 
{'start': Timestamp('2017-10-01 15:42:57'), 
'end': Timestamp('2017-10-01 17:49:59')}]
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jeff
  • 175
  • 1
  • 8

1 Answers1

0

Figured out a solution

import pandas as pd

# Create a Pandas DataFrame
df = pd.DataFrame({'Start Date': ['10/1/2017 15:23:25', '10/1/2017 15:42:57'],
    'End Date': ['10/1/2017 15:26:26', '10/1/2017 17:49:59']})

# Create a list of dictionaries
datetimes = []

# Loop over the DataFrame rows
for index, row in df.iterrows():

# Create a dictionary
dict_ = {'start': datetime.strptime(row['Start Date'], '%m/%d/%Y %H:%M:%S'), 
         'end': datetime.strptime(row['End Date'], '%m/%d/%Y %H:%M:%S')}

# Append the dictionary to the list
datetimes.append(dict_)

# Print the list of dictionaries
print(datetimes)
Jeff
  • 175
  • 1
  • 8
  • Please note that none of the supposed 5 similar solutions address what I was looking for. You might want to reconsider given I have a solution – Jeff Apr 28 '23 at 17:43