python 怎样将dataframe中的字符串日期转化为日期的方法
方法一:也是最简单的
直接使用pd.to_datetime函数实现
data['交易时间']=pd.to_datetime(data['交易时间'])
方法二:
源自利用python进行数据分析P304
使用python的datetime包中的
strptime函数,datetime.strptime(value,'%Y/%M/%D')
strftime函数,datetime.strftime(‘%Y/%M/%D')
注意使用datetime包中后面的字符串匹配需要和原字符串的格式相同,才能转义过来,相当于yyyy-mm-dd格式的需要按照'%Y-%M-%D'来实现,而不是'%Y/%M/%D'
data['交易时间']=data['交易时间'].apply(lambdax:datetime.strptime(x,'%Y-%m-%d%H:%M:%S'))
注意到上面代码的'%Y-%m-%d%H:%M:%S'嘛?
这里的格式必须与原数值的格式一模一样才能转换,如果原数值里面是精确到时分秒的,那么你此处不写%H:%M:%S就没办法转换!!!切记
''' 获取指定日期的上个月 日期字符串和日期格式 ''' defgetLastMonth(dtstr,dateformat): d=datetime.strptime(dtstr,dateformat).date() year=d.year month=d.month ifmonth==1:#如果是本年1月的 month=12 year-=1 else:#如果是大于1月的 month-=1 return(datetime(year,month,1)).strftime(dateformat) ''' 两个日期之间相差的月数 包括开始日期和结束日期的当天 日期字符串和日期格式 ''' defdiffMonth(startDate,endDate,dateformat): start=datetime.strptime(startDate,dateformat).date() end=datetime.strptime(endDate,dateformat).date() startYear=start.year startMonth=start.month endYear=end.year endMonth=end.month #如果是同年 ifstartYear==endYear: diffmonths=endMonth-startMonth #如果是上年 elifendYear-startYear==1: diffmonths=12+endMonth-startMonth #如果是大于1年 elifendYear-startYear>1: years=endYear-startYear diffmonths=(years-1)*12+12+endMonth-startMonth #如果开始日期大约结束日期报错 elifendYear-startYear<0or(endYear==startYearandendMonth-startMonth): print'enddatemustgreaterthanstartdate' returnint(diffmonths+1)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。