相当于sql for month date tim

2024-09-27 07:26:01 发布

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

我有一个需要过滤的数据帧,就像一个特定月份的sql查询一样。每次运行代码时,我都希望它从上个月获取数据,无论当前月份的具体日期是什么。你知道吗

我的SQL代码在这里,但我需要它。你知道吗

WHERE DATEPART(m, logged) = DATEPART(m, DATEADD(m, -1, getdate()))

df = pd.DataFrame({'month': ['1-05-01 00:00:00','1-06-01 00:00:00','1-06-01 00:00:00','1-05-01 00:00:00']})
df['month'] = pd.to_datetime(df['month'])```

In this example, I only want the data from June. 
Would definitely appreciate the help!  Thanks.

Tags: the数据代码dataframedfsqlwherepd
1条回答
网友
1楼 · 发布于 2024-09-27 07:26:01

根据问题编辑修改:

df = pd.DataFrame({'month': ['1-05-01 00:00:00','1-06-01 00:00:00','1-06-01 00:00:00','1-05-01 00:00:00']})
df['month'] = pd.to_datetime(df['month'])  

## To get it to the right format
import datetime as dt
df['month'] = df['month'].apply(lambda x: dt.datetime.strftime(x, '%Y-%d-%m'))
df['month'] = pd.to_datetime(df['month'])  

## Extract the month from this date
df['month_ex'] = df.month.dt.month

## Get current month to get the latest month from the dataframe, which is the previous month of the current month
from datetime import datetime
currentMonth = datetime.now().month

newDf = df[df.month_ex == currentMonth - 1]

输出:

       month  month_ex
1 2001-06-01         6
2 2001-06-01         6

相关问题 更多 >

    热门问题