Home > Back-end >  Convert 2d list to datetime in Python and then plot
Convert 2d list to datetime in Python and then plot

Time:04-13

I am trying to plot a giant 2D list of string dates onto an x axis but there are too many ticks.

Here is a shortened example of the list

[['2021-10-01 10:25:42 PM','2021-10-01 10:31:13 PM' '2021-10-01 10:31:13 PM'],['2021-10-01 10:25:42 PM','2021-10-01 10:31:13 PM' '2021-10-01 10:31:13 PM']]

I want to convert this list to datetime object so I can reduce these tick marks.

I am not sure how I can do this on a 2-D list.

For example this is not working because it is on a list.

dates_list = [datetime.strptime(date, '"%Y-%m-%d"').date() for date in valueTime_list]

CodePudding user response:

Since you can't apply strptime to a list, you have to go through the nested lists in a second loop. Besides some commas are missing in your initial valueTime_list and the format for strptime has to match the one of the lists:

from datetime import datetime
valueTime_list = [['2021-10-01 10:25:42 PM','2021-10-01 10:31:13 PM', '2021-10-01 10:31:13 PM'],['2021-10-01 10:25:42 PM','2021-10-01 10:31:13 PM', '2021-10-01 10:31:13 PM']]

dates_list = [datetime.strptime(date, '%Y-%m-%d %I:%M:%S %p').date()
              for date_lst in valueTime_list for date in date_lst]
print(dates_list)

Output:

[datetime.date(2021, 10, 1), datetime.date(2021, 10, 1), datetime.date(2021, 10, 1), datetime.date(2021, 10, 1), datetime.date(2021, 10, 1), datetime.date(2021, 10, 1)]

Edit: if you wanna keep the 2-d structure, add brackets to your comprehension:

dates_list = [[datetime.strptime(date, '%Y-%m-%d %I:%M:%S %p').date() for date in date_lst]
              for date_lst in valueTime_list]

CodePudding user response:

If you're using pandas, you can use pd.to_datetime converter:

dates_list = [pd.to_datetime(lst, infer_datetime_format=True) for lst in valueTime_list]

This will result in the same 2D list with DateTimeIndex objects (Series of datetime object).

  • Related