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实现烟花小程序的具体代码,供大家参考,具体内容如下 ''' FIREWORKS SIMULATION WITH TKINTER *self-conta...

Django进阶之CSRF的解决

Django进阶之CSRF的解决

简介 django为用户实现防止跨站请求伪造的功能,通过中间件 django.middleware.csrf.CsrfViewMiddleware 来完成。而对于django中设置防跨站...

Python实现对特定列表进行从小到大排序操作示例

本文实例讲述了Python实现对特定列表进行从小到大排序操作。分享给大家供大家参考,具体如下: 1、在系统内新建文件rizhireplacelist.txt root@kali:~#...

python中的Elasticsearch操作汇总

这篇文章主要介绍了python中的Elasticsearch操作汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 导入包 fro...

Python使用matplotlib模块绘制图像并设置标题与坐标轴等信息示例

Python使用matplotlib模块绘制图像并设置标题与坐标轴等信息示例

本文实例讲述了Python使用matplotlib模块绘制图像并设置标题与坐标轴等信息。分享给大家供大家参考,具体如下: 进行图像绘制有时候需要设定坐标轴以及图像标题等信息,示例代码如下...