首页 > 解决方案 > 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()

标签: pythonpython-3.xpandasdatetimeformatting

解决方案


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

推荐阅读