有时,我们需要对日期进行简单的运算,这就要使用到了日期运算和转换的函数。
例如:

其中使用pd.to_datetime可以统一将time.strftime("%Y/%m/%d")生成的日期转换成日期格式的数据。time.strftime("%Y/%m/%d")生成的日期为字符串格式。
一、计算两组时间之间的间隔
在图中有两列的日期,我们可以直接求出它们之间的间隔,在计算之前要先确定一下日期列的数据是否是日期格式:

确定了都是日期格式就可以进行日期的计算:


由上图可知,计算后的日期天数却有着一个days单位,这个 因为这个是属于timedelta64[ns]的数据属性:

因此我们可以将其转换成整数,以方便我们后续的使用:

使用pd.to_numeric可以将其它形式的数据转换成整数型的数据。
我们在看看现在数据的类型:

当然了,也可以使用函数来进行转换:

使用匿名函数的时候对每个元素使用一次.days就能将数据转换成整数。
timedelta的数据类型相互直接不能转换成年、周、月等,只能转换为天数、秒数、微妙数。而且在返回秒数和微笑数时,如果是负数时容易出错(例如:-3秒会被处理为-1天86397秒):

在两个日期直接进行计算之后:

所以在日期计算之后为负数的时候就会出错,因此在转换间隔秒数的时候最后使用total_seconds()函数(记得函数后面的括号):

网友评论