熊猫相当于月份日期时间的sql

时间:2019-07-23 19:44:53

标签: python pandas date

我有一个熊猫数据框,需要过滤,就像特定月份的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.

1 个答案:

答案 0 :(得分:1)

根据问题进行修改:

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