python 怎樣將dataframe中的字符串日期轉(zhuǎn)化為日期的方法
方法一:也是最簡單的
直接使用pd.to_datetime函數(shù)實現(xiàn)
data['交易時間'] = pd.to_datetime(data['交易時間'])
方法二:
源自利用python進行數(shù)據(jù)分析P304
使用python的datetime包中的
strptime函數(shù),datetime.strptime(value,'%Y/%M/%D')
strftime函數(shù),datetime.strftime(‘%Y/%M/%D')
注意使用datetime包中后面的字符串匹配需要和原字符串的格式相同,才能轉(zhuǎn)義過來,相當于yyyy-mm-dd格式的需要按照'%Y-%M-%D'來實現(xiàn),而不是'%Y/%M/%D'
data['交易時間']=data['交易時間'].apply(lambda x:datetime.strptime(x,'%Y-%m-%d %H:%M:%S'))
注意到上面代碼的'%Y-%m-%d %H:%M:%S'嘛?
這里的格式必須與原數(shù)值的格式一模一樣才能轉(zhuǎn)換,如果原數(shù)值里面是精確到時分秒的,那么你此處不寫%H:%M:%S就沒辦法轉(zhuǎn)換!!!切記
''' 獲取指定日期的上個月 日期字符串和日期格式 ''' 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) ''' 兩個日期之間相差的月數(shù) 包括開始日期和結(jié)束日期的當天 日期字符串和日期格式 ''' 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 #如果開始日期大約結(jié)束日期報錯 elif endYear-startYear<0 or( endYear==startYear and endMonth-startMonth): print 'enddate must greater than startdate' return int(diffmonths+1)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python numpy中的polyfit函數(shù)用法
這篇文章主要介紹了python numpy中的polyfit函數(shù)用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04Python獲取和設(shè)置代理的動態(tài)IP的方式
在網(wǎng)絡(luò)世界中,代理和動態(tài)IP是非常常見的概念,尤其對于需要大規(guī)模訪問網(wǎng)站或者需要隱藏真實IP地址的應(yīng)用程序來說,更是必不可少的工具,本文將給大家介紹如何使用編程技術(shù)來實現(xiàn)動態(tài)IP的設(shè)置和管理,需要的朋友可以參考下2024-05-05Python THREADING模塊中的JOIN()方法深入理解
這篇文章主要介紹了Python THREADING模塊中的JOIN()方法深入理解,本文用簡潔易懂的語言總結(jié)了對JOIN()方法的理解,不同于其它文章,需要的朋友可以參考下2015-02-02