[英]Converting a string to to date using Python and datetime
I have a column that contains stings in the form 'yyyymmdd' as below; 我有一列包含“ yyyymmdd”形式的字符串,如下所示;
Start_date
20081201
20120823
20101210
I want to be able to convert these into actual dates and am looking at using datetime
. 我希望能够将这些转换为实际日期,并正在考虑使用
datetime
。 From looking online I have managed to get to define both of the following functions. 通过在线查找,我设法定义了以下两个功能。
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
I have then tried applying these using the apply
function as below 然后我尝试使用如下的
apply
函数来应用这些
Dates['Newdates'] = Dates['Start_date'].apply(get_datetime)
However I keep getting the following error 但是我不断收到以下错误
TypeError: 'long' object has no attribute '__getitem__'
Even though the values in the fields are Integers! 即使字段中的值是整数!
You need to cast the date to a string first. 您需要先将日期转换为字符串。
import datetime as dt
dt.datetime.strptime(str(20081201), '%Y%m%d').strftime('%m/%d/%Y')
Will return 将返回
'12/01/2008'
The full solution I used was the following 我使用的完整解决方案如下
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.