![](/img/trans.png)
[英]What is the "+01:00" in "2006-04-03 08:00:00+01:00" datetime timestamp object?
[英]How to Convert Datetime column header (e.g. 2007-03-01 00:00:00) into Date-Month-Year format i.e. 2007-03-01
如何将日期时间列标题(例如 2007-03-01 00:00:00)转换为日期-月-年格式,即 2007-03-01?
我试过
df=pd.DataFrame({'Company Name':['3M India Ltd.','A B B India Ltd.'],'2007-03-01 00:00:00':[1571.30,710.20],'2007-04-01 00:00:00':[710.20,818.13]})
df.columns=pd.to_datetime.date(df.columns)
但显示错误 AttributeError: 'function' object has no attribute 'date'
首先通过set_index
而非 datetimes 列创建index
,然后使用to_datetime
并在必要时将date
添加DatetimeIndex.date
:
df = df.set_index('Company Name')
df.columns = pd.to_datetime(df.columns).date
print (df)
2007-03-01 2007-04-01
Company Name
3M India Ltd. 1571.3 710.20
A B B India Ltd. 710.2 818.13
另一种解决方案,如果不可能,第一个是可以通过columns
创建Series
,然后调用to_datetime
with errors='coerce'
将所有值从列转换为日期时间,因为不是日期返回NaT
(日期时间的缺失值),所以最后添加fillna
将非日期时间替换为原始列名称:
s = pd.Series(df.columns)
df.columns = pd.to_datetime(s, errors='coerce').dt.date.fillna(s)
print (df)
Company Name 2007-03-01 2007-04-01
0 3M India Ltd. 1571.3 710.20
1 A B B India Ltd. 710.2 818.13
详情:
print (pd.to_datetime(s, errors='coerce'))
0 NaT
1 2007-03-01
2 2007-04-01
dtype: datetime64[ns]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.