【问题标题】:How to change date time format of column in pandas data frame如何更改熊猫数据框中列的日期时间格式
【发布时间】:2019-11-13 02:54:39
【问题描述】:

我有数据框 (df2)。它有列(日期),其中包含格式为“Mon Aug 10 11:06:25 UTC 2015”的一些日期和时间,我必须将其更改为“2015 年 8 月 10 日 11:06:25”格式。

我尝试了以下代码,但它给出了错误

df2['date'] = pd.to_datetime(df2['date'], errors='coerce')
df2['date'] = df2['date'].dt.strftime('%b %d %H:%M:%S %Y')
df2

    ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2896             try:
-> 2897                 return self._engine.get_loc(key)
   2898             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'date'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-403-66f0c1caed0e> in <module>
      1 df2 = df2.rename(columns = {'Mon Aug 10 07:56:39 UTC 2015': 'date'})
      2 
----> 3 df2['date'] = pd.to_datetime(df2['date'], errors='coerce')
      4 df2['date'] = df2['date'].dt.strftime('%b %d %H:%M:%S %Y')
      5 df2

~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2978             if self.columns.nlevels > 1:
   2979                 return self._getitem_multilevel(key)
-> 2980             indexer = self.columns.get_loc(key)
   2981             if is_integer(indexer):
   2982                 indexer = [indexer]

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2897                 return self._engine.get_loc(key)
   2898             except KeyError:
-> 2899                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2900         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2901         if indexer.ndim > 1 or indexer.size > 1:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'date'

【问题讨论】:

  • 如果您正在考虑编写循环或使用apply,那么您可能错误地使用了pandas。请参阅以下优雅代码的答案。

标签: python-3.x pandas datetime-format


【解决方案1】:

最简单的方法是:

import pandas as pd
df2['date'] = pd.to_datetime(df2['date'], errors='coerce')
df2['date'] = df2['date'].dt.strftime('%b %d %H:%M:%S %Y')

我很确定这将解决您的主要问题。 documentation

从那时起,您可以更轻松地操作pd.Timestamp 对象以显示您想要的任何格式。

祝你好运。如果这对您有用,或者您需要进一步的帮助,请告诉我。

编辑: @AsraKhalid,我怀疑您的错误根源实际上在第一行: df2 = df2.rename(columns = {'Mon Aug 10 07:56:39 UTC 2015 ': '日期'})。您可能认为您正在更改列名,但实际上有一个错字,但没有报告,因为 df.rename 默认情况下会抑制错误。尝试将其更改为 df2 = df2.rename(columns = {'Mon Aug 10 07:56:39 UTC 2015': 'date'}, errors="raise")。这样,您将看到 'Mon Aug 10 07:56:39 UTC 2015' 实际上是否在 df 中,或者您是否拼写错误

【讨论】:

  • 我在代码中添加了格式参数:df2['date'] = pd.to_datetime(df2['date'], format = '%m %d %H:%M:%S % Y') 但它以这种格式给出输出:2015-08-11 07:08:12+00:00 你能找出代码中有什么问题吗?
  • @AsraKhalid 没有错。那只是一种显示格式。
  • @AsraKhalid,您可以添加 df2['date'] = df2['date'].dt.strftime('%m %d %H:%M:%S %Y'),但请注意,它会将您的列类型从 pd.Timestamp 更改为对象(字符串)。我将此更改添加到答案中。请让我知道它是否适合您。 to_datetime() 中不需要format = '%m %d %H:%M:%S %Y',它实际上可能会干扰,我会删除它。
  • df2['date'] = df2['date'].dt.strftime('%b %d %H:%M:%S %Y') 生成错误:AttributeError: Can仅使用带有 datetimelike 值的 .dt 访问器
  • @AsraKhalid,我很确定问题是您有一些日期无法转换为时间戳。要解决此问题,请尝试将第二行更改为 df2['date'] = pd.to_datetime(df2['date'], errors='coerce')。我将在答案本身中添加此修复程序。
【解决方案2】:

您可以使用 pandas 的 apply() 方法。请检查 date formats 我不明白为什么您的时间戳中有 UTC 字符串。但根据您的问题,请尝试以下代码:

from datetime import datetime

def change_date_string(date_string):

   date_string = str(date_string).replace('UTC', '')
   date_object = datetime.strptime(date_string, "%a %b %d %H:%M:%S %Y").strftime('%b %d %H:%M:%S %Y')
   return date_object

df2['date'] = df2['date'].apply(change_date_string)

例子:

from datetime import datetime

date_string = 'Mon Aug 10 11:06:25 UTC 2015'
date_string = str(date_string).replace('UTC', '')
date_object = datetime.strptime(date_string, "%a %b %d %H:%M:%S %Y").strftime('%b %d %H:%M:%S %Y')
print(date_object)

输出:

Aug 10 11:06:25 2015

请注意输出将是字符串格式

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 2017-05-21
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多