【问题标题】:How to convert a numpy array string to datetime如何将numpy数组字符串转换为日期时间
【发布时间】:2021-11-26 08:50:40
【问题描述】:

我有以下 numpy 数组

array(['2/25/2019 9:55:01 PM', '2/25/2019 10:00:00 PM',
       '2/25/2019 10:05:00 PM', '2/25/2019 10:10:00 PM',
       '2/25/2019 10:15:00 PM', '2/25/2019 10:20:00 PM',
       '2/25/2019 10:25:00 PM', '2/25/2019 10:30:00 PM',
       '2/25/2019 10:35:00 PM', '2/25/2019 10:40:00 PM',
       '2/25/2019 10:45:00 PM', '2/25/2019 10:50:00 PM',
       '2/25/2019 10:55:00 PM', '2/25/2019 11:00:00 PM',
       '2/25/2019 11:05:00 PM', '2/25/2019 11:10:00 PM'], dtype=object)

这个 numpy 数组中的所有日期都是 str 类型。现在我想将这个numpy数组中的所有元素从str类型转换为datetime。

我知道我可以通过循环来做到这一点,但是由于numpy数组的大小非常大,所以有什么方法可以不使用迭代来转换它们吗?

【问题讨论】:

  • 转换为datetime.datetime 对象必须在循环中。如果字符串格式正确,可以使用astype 转换为np.datetime64 dtype。

标签: python pandas numpy datetime


【解决方案1】:

试试:

import pandas as pd
your_array = pd.to_datetime(your_array).to_numpy()

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 1970-01-01
    • 2015-01-22
    • 2022-08-18
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多