Praveen Snowy
Praveen Snowy

Reputation: 163

How to find the next month and current month datetime in python

I need to find the next month and current month Datetime in python

I have a dataframe which has date columns and i need to filter the values based on todays date.
if todays date is less than 15, i need all row values starting from current month (2019-08-01 00:00:00)
if todays date is >=15, i need all row values starting from next month(2019-09-01 00:00:00)

Dataframe:

      PC  GEO        Month             Values
      A   IN    2019-08-01 00:00:00     1
      B   IN    2019-08-02 00:00:00     1
      C   IN    2019-09-14 00:00:00     1
      D   IN    2019-10-01 00:00:00     1
      E   IN    2019-07-01 00:00:00     1

if today's date is < 15

      PC  GEO        Month             Values
      A   IN    2019-08-01 00:00:00     1
      B   IN    2019-08-02 00:00:00     1
      C   IN    2019-09-14 00:00:00     1
      D   IN    2019-10-01 00:00:00     1

if today's date is >= 15

      PC  GEO        Month             Values
      C   IN    2019-09-14 00:00:00     1
      D   IN    2019-10-01 00:00:00     1

I am passing todays date as below
dat = date.today()
dat = dat.strftime("%d")
dat = int(dat)

Upvotes: 1

Views: 6963

Answers (1)

jezrael
jezrael

Reputation: 862511

Use:

#convert column to datetimes
df['Month'] = pd.to_datetime(df['Month'])

#get today timestamp
dat = pd.to_datetime('now')
print (dat)
2019-08-27 13:40:54.272257

#convert datetime to month periods
per = df['Month'].dt.to_period('m')
#convert timestamp to period
today_per = dat.to_period('m')


#compare day and filter
if dat.day < 15:
    df = df[per >= today_per]
    print (df)
else:
    df = df[per > today_per]
    print (df)
      PC GEO      Month  Values
    2  C  IN 2019-09-14       1
    3  D  IN 2019-10-01       1

Test with values <15:

df['Month'] = pd.to_datetime(df['Month'])

dat = pd.to_datetime('2019-08-02')
print (dat)
2019-08-02 00:00:00

per = df['Month'].dt.to_period('m')
today_per = dat.to_period('m')

if dat.day < 15:
    df = df[per >= today_per]
    print (df)

      PC GEO      Month  Values
    0  A  IN 2019-08-01       1
    1  B  IN 2019-08-02       1
    2  C  IN 2019-09-14       1
    3  D  IN 2019-10-01       1

    else:
        df = df[per > today_per]

Upvotes: 0

Related Questions