python 怎样将dataframe中的字符串日期转化为日期的方法

yipeiwu_com6年前Python基础

方法一:也是最简单的

直接使用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(lambda x:datetime.strptime(x,'%Y-%m-%d %H:%M:%S'))

注意到上面代码的'%Y-%m-%d %H:%M:%S'嘛?

这里的格式必须与原数值的格式一模一样才能转换,如果原数值里面是精确到时分秒的,那么你此处不写%H:%M:%S就没办法转换!!!切记

'''
获取指定日期的上个月
日期字符串和日期格式
'''
def getLastMonth(dtstr,dateformat):
 d=datetime.strptime(dtstr, dateformat).date()
 year = d.year
 month = d.month
 if month == 1 :#如果是本年1月的
 month = 12
 year -= 1
 else :#如果是大于1月的
 month -= 1
 return (datetime(year,month,1)).strftime(dateformat)
 
'''
两个日期之间相差的月数
包括开始日期和结束日期的当天
日期字符串和日期格式
''' 
def diffMonth(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
 
 #如果是同年
 if startYear==endYear:
 diffmonths=endMonth-startMonth
 #如果是上年
 elif endYear-startYear==1:
 diffmonths=12+endMonth-startMonth
 #如果是大于1年
 elif endYear-startYear>1:
 years=endYear-startYear
 diffmonths=(years-1)*12+12+endMonth-startMonth
 #如果开始日期大约结束日期报错
 elif endYear-startYear<0 or( endYear==startYear and endMonth-startMonth):
 print 'enddate must greater than startdate'
 
 return int(diffmonths+1)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现的排列组合计算操作示例

Python实现的排列组合计算操作示例

本文实例讲述了Python实现的排列组合计算操作。分享给大家供大家参考,具体如下: 1. 调用 scipy 计算排列组合的具体数值 >> from scipy.spec...

Python切片知识解析

切片原型 strs = ‘abcdefg' Strs[start: end:step] 切片的三个参数分别表开始,结束,步长 第一位下标为0,end位不取,如strs[1:3] = ‘b...

Python 遍历子文件和所有子文件夹的代码实例

Python 遍历子文件和所有子文件夹的代码实例

最近看ECShop到网上找资料,发现好多说明ECShop的文件结构不全面,于是想自己弄个出来。但这是个无聊耗时的工作,自己就写了个Python脚本,可以递归遍历目录下的所有文件和所有子目...

Python实战小程序利用matplotlib模块画图代码分享

Python实战小程序利用matplotlib模块画图代码分享

Python中的数据可视化 matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件。...

Pycharm2017版本设置启动时默认自动打开项目的方法

Pycharm2017版本设置启动时默认自动打开项目的方法

最新版本不同于旧版本的设置,网上检索一番方法都不适用。 新版的设置位置在“configure->setting->Appearance&Behavior->System...