Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何更改熊猫数据框中列的日期时间格式_Python 3.x_Pandas_Datetime Format - Fatal编程技术网

Python 3.x 如何更改熊猫数据框中列的日期时间格式

Python 3.x 如何更改熊猫数据框中列的日期时间格式,python-3.x,pandas,datetime-format,Python 3.x,Pandas,Datetime Format,我有数据帧(df2)。它有一列(日期),其中包含一些日期和时间,格式为“2015年8月10日星期一11:06:25 UTC”,我必须将其更改为“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 ------------

我有数据帧(df2)。它有一列(日期),其中包含一些日期和时间,格式为“2015年8月10日星期一11:06:25 UTC”,我必须将其更改为“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'
df2['date']=pd.to_datetime(df2['date'],errors='concurve')

df2['date']=df2['date'].dt.strftime(“%b%d%H:%M:%S%Y”) df2 --------------------------------------------------------------------------- KeyError回溯(最近一次呼叫最后一次) get\u loc中的~\Anaconda3\lib\site packages\pandas\core\index\base.py(self、key、method、tolerance) 2896尝试: ->2897自动返回发动机。获取位置(钥匙) 2898除按键错误外: 熊猫\\u libs\index.pyx在熊猫中。\ u libs.index.IndexEngine.get_loc() 熊猫\\u libs\index.pyx在熊猫中。\ u libs.index.IndexEngine.get_loc() pandas\\u libs\hashtable\u class\u helper.pxi在pandas.\u libs.hashtable.PyObjectHashTable.get\u item()中 pandas\\u libs\hashtable\u class\u helper.pxi在pandas.\u libs.hashtable.PyObjectHashTable.get\u item()中 KeyError:“日期” 在处理上述异常期间,发生了另一个异常: KeyError回溯(最近一次呼叫最后一次) 在里面 1 df2=df2.重命名(列={'Mon Aug 10 07:56:39 UTC 2015':'date'}) 2. ---->3 df2['date']=pd.to_datetime(df2['date'],errors='Procure')
4 df2['date']=df2['date'].dt.strftime(“%b%d%H:%M:%S%Y”) 5 df2 ~\Anaconda3\lib\site packages\pandas\core\frame.py in\uuuu\getitem\uuuuuuu(self,key) 2978如果self.columns.nlevels>1: 2979返回自我。\u获取项目\u多级(键) ->2980索引器=self.columns.get_loc(键) 2981如果是_整数(索引器): 2982索引器=[索引器] get\u loc中的~\Anaconda3\lib\site packages\pandas\core\index\base.py(self、key、method、tolerance) 2897自动返回发动机。获取位置(钥匙) 2898除按键错误外: ->2899返回self.\u引擎。获取self.\u loc(self.\u可能\u cast\u索引器(键)) 2900 indexer=self.get_indexer([key],method=method,tolerance=tolerance) 2901如果indexer.ndim>1或indexer.size>1: 熊猫\\u libs\index.pyx在熊猫中。\ u libs.index.IndexEngine.get_loc() 熊猫\\u libs\index.pyx在熊猫中。\ u libs.index.IndexEngine.get_loc() pandas\\u libs\hashtable\u class\u helper.pxi在pandas.\u libs.hashtable.PyObjectHashTable.get\u item()中 pandas\\u libs\hashtable\u class\u helper.pxi在pandas.\u libs.hashtable.PyObjectHashTable.get\u item()中 KeyError:“日期”
最简单的方法是:

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')
我相信这会解决你的主要问题。这个

从那时起,您可以更轻松地操纵对象以显示所需的任何格式

祝你好运。请让我知道这是否对您有效,或者您是否需要进一步的帮助

编辑:@AsraKhalid,我怀疑您的错误源实际上在第一行:df2=df2.rename(columns={'Mon Aug 10 07:56:39 UTC 2015':'date'})。您可能认为您正在更改列名,但实际上有一个输入错误,但没有报告,因为默认情况下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中,或者如果拼写错误,您可以使用pandas apply()方法。请检查“我不明白为什么时间戳中有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

请注意,输出将采用字符串格式

如果您正在考虑编写循环或使用
apply
,则可能使用了错误的方法。请用优雅的代码查看下面的答案。我在代码中添加了格式参数: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更改为object(string)。我在答案上加了这个改动。请让我知道它是否适合你。不需要
格式='%m%d%H:%m:%S%Y'
在to_datetime()中,它实际上可能会干扰,我将删除它。df2['date']=df2['date'].dt.strftime('%b%d%H:%m:%S%Y')生成一个错误:AttributeError:只能使用具有datetimelike的.dt访问器values@AsraKhalid,我很确定问题在于,有些日期无法转换为时间戳。要解决此问题,请尝试将第二行更改为
df2['date']=pd.To_datetime(df2['date'],errors='concurve')
。我将在答案中添加此修复。