如何在 Python 中获取文件创建到我的数据框中的日期?

How can I get the date a file was created into my dataframe in Python?

我现在的df是这样的-

Company State Address Zip    City
ABC      CA   1 st    86284  LA

所有这些数据都是从每月放在目录中的文件中提取的。

我想要另一列表示文件在目录中 created/dropped 的月份减 1(文件日期减 1 个月)。所以基本上,如果文件是在 22 年 5 月 5 日创建的。我想要下面的

Company State Address Zip    City  File Month
ABC      CA   1 st    86284  LA    04-2022

我的尝试-

import datetime
import os
# Path to the file
path = r"E:\demos\files_demos\sample.txt"

# file creation timestamp in float
c_time = os.path.getctime(path)
# convert creation timestamp into DateTime object
dt_c = datetime.datetime.fromtimestamp(c_time)
df['File Month'] = dt_c
2022-05-05 17:21:57.914774

但这就是给了我上面的内容。有更好的方法吗?

您可以从每个日期中减去一个pd.tseries.offsets.MonthEnd,并使用strftime:

df['File Month'] = df['File Month'].sub(pd.tseries.offsets.MonthEnd()).dt.strftime('%m-%Y')

您可以根据日期时间对象计算上个月并将其转换为所需的字符串格式

df['File Month'] = (dt_c.replace(day=1) - datetime.timedelta(days=1)).strftime("%m-%Y")
  Company State Address    Zip City File Month
0     ABC    CA    1 st  86284   LA    04-2022