Reputation: 465
I'm trying to change the datetime objects in a list-of-lists to strings using strftime, but the conversion to string is acting confusingly. Specifically, I'm trying to format it as %H:%M
I've parsed an Excel file with Pandas and converted the DataFrame into a list-of-lists using NumPy.
Here's the relevant section(s) of my code
import pandas as pd
import datetime
import time
...
dataframe = pd.read_excel(download_file, skiprows=4)
location_logs = dataframe.to_numpy().tolist()
for log in location_logs:
for val in log:
if type(val) == datetime.datetime:
val = val.strftime("%H:%M")
The loop is identifying datetime objects correctly as a print statement inside the conditional matches the data and even prints the formatted string instead of the datetime object.
However, if I print a list such as location_logs[0]
, it prints the datetime object found in the nested list instead of the string, i.e., printing datetime.datetime(2019,6,17,23,59)
instead of my expected 23:59
Am I going about converting datetime objects incorrectly? Is it possible the size of the list-of-lists is causing an issue? There are ~62k lists with 7 elements in each list.
Upvotes: 0
Views: 488
Reputation: 4827
Maybe try something like:
location_logs = [datetime.datetime(2009, 9, 12, 11, 23, 44), datetime.datetime(2019, 7, 10, 6, 21, 15)]
for i in range(len(location_logs)):
if type(location_logs[i]) == datetime.datetime:
location_logs[i] = location_logs[i].strftime("%H:%M")
location_logs
Result:
['11:23', '06:21']
Upvotes: 1