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