python - Python datetime delta format
问题描述
I am attempting to find records in my dataframe that are 30 days old or older. I pretty much have everything working but I need to correct the format of the Age column. Most everything in the program is stuff I found on stack overflow, but I can't figure out how to change the format of the delta that is returned.
import pandas as pd
import datetime as dt
file_name = '/Aging_SRs.xls'
sheet = 'All'
df = pd.read_excel(io=file_name, sheet_name=sheet)
df.rename(columns={'SR Create Date': 'Create_Date', 'SR Number': 'SR'}, inplace=True)
tday = dt.date.today()
tdelta = dt.timedelta(days=30)
aged = tday - tdelta
df = df.loc[df.Create_Date <= aged, :]
# Sets the SR as the index.
df = df.set_index('SR', drop = True)
# Created the Age column.
df.insert(2, 'Age', 0)
# Calculates the days between the Create Date and Today.
df['Age'] = df['Create_Date'].subtract(tday)
The calculation in the last line above gives me the result, but it looks like -197 days +09:39:12
and I need it to just be a positive number 197
. I have also tried to search using the python, pandas, and datetime keywords.
df.rename(columns={'Create_Date': 'SR Create Date'}, inplace=True)
writer = pd.ExcelWriter('output_test.xlsx')
df.to_excel(writer)
writer.save()
解决方案
I can't see your example data, but IIUC and you're just trying to get the absolute value of the number of days of a timedelta, this should work:
df['Age'] = abs(df['Create_Date'].subtract(tday)).dt.days)
Explanation:
Given a dataframe with a timedelta column:
>>> df
delta
0 26523 days 01:57:59
1 -1601 days +01:57:59
You can extract just the number of days as an int
using dt.days
:
>>> df['delta']dt.days
0 26523
1 -1601
Name: delta, dtype: int64
Then, all you need to do is wrap that in a call to abs
to get the absolute value of that int:
>>> abs(df.delta.dt.days)
0 26523
1 1601
Name: delta, dtype: int64
推荐阅读
- python - 如何在 Django 中的多对多关系中向数据透视表添加更多列?
- python - 获取文本并删除所有标签,但保留标题和粗体的标签
- excel - excel + vba + 编译错误 AutoOpenRequiredWorkbook (myFileNameToOpen, myFilePath) 无法弄清楚为什么我会收到此错误
- javascript - 基于具有唯一值的数组创建多个动态选择过滤器以过滤 Vue.js 中的另一个数组
- sql - 使用 SQL Server:如何使用基于 sum 的选择条件
- python - 每列中唯一值的切割表
- c# - 如何在基于部署环境的静态类中加载 appsettings.json,以便我可以在其他类库中使用
- javascript - 为什么我需要 setTimeout.bind(window)
- python - Euler 项目中的意外输出(项目编号 3)
- python - “TypeError:列表索引必须是整数或切片,而不是元组” - 如何将列表项放入矩阵