【问题标题】:converting an array of strings into datetimes python for matplotlibpython将字符串数组转换为matplotlib的日期时间
【发布时间】:2017-03-24 02:07:55
【问题描述】:

我正在尝试使用 for 循环将 times_from_text_file 数组中的时间字符串数组转换为日期时间,然后我想将这些日期时间与另一个名为 temperature 的数组进行对比,打印 false 并返回温度数组的值。如果温度数组中的所有值都相同,则唯一一次什么都不会被绘制,只是真正打印。我遇到的问题是将 times_from_text_file 数组中的所有字符串时间转换为日期时间,这会导致以下错误。

def values_equal_np_array(temp, time_created_index, time_modified_index, times_from_text_file):
    if (len(np.unique(temp)) == 1):
        return True
    else:
        #tells user the temps are not equal for a specified interval of time
        print ('False')

        plt.xlabel('Time')
        plt.ylabel('Temperature')
        plt.title('Time vs Temperature')        

        #specifying the beginning to end interval of temperature collection
        final_times = times_from_text_file[time_created_index:`time_modified_index]                  

        for i in range(len(final_times)):
            new_time = datetime.datetime.strptime(final_times, "%H:%M")
            datetimes.append(new_time)
            new_array[i] = new_time

        final_times = matplotlib.dates.date2num(new_time)
        matplotlib.pyplot.plot_date(new_array, temp)
        plt.show()

        #the values that appear in the non-uniform temperature array on display      
        return np.unique(temp)

#testing the function 
values_equal_np_array([1, 1, 1, 2, 3, 4], 3, 8, ['10:15','12:31','12:32','1:33', '12:34', '1:35', '2:36', '2:37', '3:38', '1:39'])

False

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-6151e84dc0c7> in <module>()
----> 1 values_equal_np_array([1, 1, 1, 2, 3, 4], 3, 8, ['10:15','12:31','12:32','1:33', '12:34', '1:35', '2:36', '2:37', '3:38', '1:39'])

<ipython-input-10-96555d9f1618> in values_equal_np_array(temp, time_created_index, time_modified_index, times_from_text_file)
     15 
     16         for i in range(len(final_times)):
---> 17             new_time = datetime.datetime.strptime(final_times, "%H:%M")
     18             datetimes.append(new_time)
     19             new_array[i] = new_time

TypeError: strptime() argument 1 must be str, not list

【问题讨论】:

    标签: python arrays datetime matplotlib


    【解决方案1】:

    使用list comprehension

    new_times = [datetime.datetime.strptime(x, "%H:%M") for x in final_times]
    

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2016-02-18
      • 2021-06-01
      • 2012-06-04
      • 1970-01-01
      • 2016-04-22
      • 2022-08-18
      • 2019-05-15
      • 2022-01-23
      相关资源
      最近更新 更多