程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Date time interval operation of pandas (pd.to_datetime and pd.to_numeric)

編輯:Python

Reprinted from :https://www.jianshu.com/p/26c48361ed24

Sometimes , We need to do a simple calculation on the date , This requires the use of date operations and conversion functions .

for example :

Source data

It uses pd.to_datetime Can unify time.strftime("%Y/%m/%d") The generated date is converted to data in date format .time.strftime("%Y/%m/%d") The generated date is in string format .

One 、 Calculate the interval between two sets of time

Date with two columns in the graph , We can find the distance between them directly , Before calculation, you should first determine whether the data in the date column is in date format :

data format

Date calculation can be carried out after the date format is determined :

Calculation of date

 

Days after calculation

It can be seen from the above figure , The calculated date days have a days Company , This Because this belongs to timedelta64[ns] Data properties for :

Calculated data attributes

So we can convert it to an integer , To facilitate our subsequent use :

Convert data type to integer

Use pd.to_numeric It can convert other forms of data into integer data .

We are looking at the current data types :

Converted data type

Yes, of course , You can also use functions to convert :

Use anonymous function to convert to integer type

Use anonymous functions once for each element .days You can convert data into integers .

timedelta The data types of are not directly convertible to each other 、 Zhou 、 Month etc , Can only be converted to days 、 Number of seconds 、 Subtle numbers . And when returning seconds and smiles , If it is negative, it is easy to make mistakes ( for example :-3 Seconds will be processed as -1 God 86397 second ):

Source data

After two dates are calculated directly :

Calculated data

So there will be an error when the date is negative after the calculation , Therefore, when converting the interval seconds, use the last total_seconds() function ( Remember the parentheses after the function ):

Use total_seconds() function

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved