Python日期时间增量形式

2024-06-28 14:53:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的数据帧中找到30天或更久的记录。我几乎所有的工作,但我需要纠正的年龄列格式。程序中的大部分内容都是我在堆栈溢出中找到的,但我不知道如何更改返回的增量的格式。你知道吗

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)

上面最后一行中的计算给出了结果,但它看起来像-197 days +09:39:12,我需要它只是一个正数197。我还尝试使用python、pandas和datetime关键字进行搜索。你知道吗

df.rename(columns={'Create_Date': 'SR Create Date'}, inplace=True)

writer = pd.ExcelWriter('output_test.xlsx')
df.to_excel(writer)
writer.save()

Tags: thenametruedfagedateascreate
1条回答
网友
1楼 · 发布于 2024-06-28 14:53:27

我看不到你的示例数据,但IIUC和你只是想得到一个timedelta的天数的绝对值,这应该是可行的:

df['Age'] =  abs(df['Create_Date'].subtract(tday)).dt.days)

解释:

给定一个带有timedelta列的数据帧:

>>> df
                 delta
0  26523 days 01:57:59
1 -1601 days +01:57:59

您可以使用dt.days将天数提取为int

>>> df['delta']dt.days
0    26523
1    -1601
Name: delta, dtype: int64

然后,您需要做的就是将其包装在对abs的调用中,以获得该int的绝对值:

>>> abs(df.delta.dt.days)
0    26523
1     1601
Name: delta, dtype: int64

相关问题 更多 >