2017-09-05 107 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) 
相關問題