python 怎樣將dataframe中的字符串日期轉化爲日期的方法

這篇文章主要介紹了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(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腳本、爬蟲、django、數據挖掘等編程技術,工作經驗,還有前輩精心爲學習python的小夥伴整理零基礎到項目實戰的資料,!每天都有程序員定時講解Python技術,分享一些學習的方法和需要留意的小細節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章