2017-09-05 106 views
-1

我有一列包含以下形式'yyyymmdd'的叮咬;使用Python和日期时间将字符串转换为日期

Start_date 
20081201 
20120823 
20101210 

我希望能够将这些转化为实际的日期,期待在使用datetime。从网上查看,我设法定义了以下两个功能。

def dateconvert(Start_date): 
    dateconv = datetime.strptime(Start_date, '%Y%m%d').strftime('%m/%d/%Y') 
    return dateconv 

def get_datetime(date_string): 
    newdate = datetime.date(date_string[:3],date_string[4:6],date_string[6:8]) 
    return newdate 

我已经然后尝试这些使用apply功能如下

Dates['Newdates'] = Dates['Start_date'].apply(get_datetime) 

不过,我不断收到以下错误

TypeError: 'long' object has no attribute '__getitem__' 

即使在字段中的值是整数应用!

+0

这可能是建设性的解决你的功能内置Python类型在尝试使用它们之前与numpy串联。例如,你期望'get_datetime(20081201)'返回什么,它实际返回了什么? – Kevin

回答

2

您需要先将日期转换为字符串。

import datetime as dt 
dt.datetime.strptime(str(20081201), '%Y%m%d').strftime('%m/%d/%Y') 

将返回

'12/01/2008' 
0

我使用的完整的解决方案,在以下

import datetime as dt 

def dateconvert(Start_date): 
    Date_String = str(Start_date) 
    dateconv = dt.datetime.strptime(Date_String, '%Y%m%d').strftime('%m/%d/%Y') 
    return dateconv 

Dates['Newdates'] = Dates['Start_date'].apply(dateconvert) 
相关问题