Skip to main content
 首页 » 编程设计

python之你能在不知道格式的情况下使用 datetime.strptime 吗

2025年05月04日11bjzhanghao

我正在编写一个包含 3 个 pandas 系列的函数,其中一个是日期,我需要能够将它变成一个数据框,以便我可以对它们进行重新采样。问题是,当我简单地执行以下操作时:

>>> data.index = data.time 
>>> df = data.resample('M') 

我收到以下错误:

Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/generic.py", line 234, in resample 
    return sampler.resample(self) 
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/tseries/resample.py", line 100, in resample 
    raise TypeError('Only valid with DatetimeIndex or PeriodIndex') 
TypeError: Only valid with DatetimeIndex or PeriodIndex 

我知道这是因为即使索引类型是 datetime 对象,在进行重采样时,除非它的形式是 datetime(x,x,x,x,x,x),它不会正确读取它。

所以当我使用它时,我的日期数据看起来像这样:2011-12-16 08:09:07,所以我一直在做以下事情:

dates = data.time 
date_objects = [datetime.strptime(dates[x], '%Y-%m-%d %H:%M:%S') for x in range(len(dates))] 
data.index = date_objects  
df = data.resample('M') 

我的问题是我将它用于开源,我不知道输入时日期的格式。

所以我的问题是:如何在不知道字符串格式化方式的情况下将带有日期和时间的字符串转换为日期时间对象?

请您参考如下方法:

您可以为此目的使用dateutil 库

from dateutil import parser 
yourdate = parser.parse(dates[x])