0

Trying to get end of month data with datetime.

my code:

monthyear = input("Enter Full Month and Year: ")   #Ie September 2021
assessdate = pd.to_datetime(prevdate, format="%B %Y").strftime('%m%d%Y %H:%M')

getting

09012021 00:00

expecting:

09/30/2021 00:00

tried:

monthyear = input("Enter Full Month and Year: ")   #Ie September 2021
assessdate = pd.to_datetime(monthyear, format="%B %Y")+MonthEnd(1).dt.strftime('%m%d%Y %H:%M')
Jonnyboi
  • 505
  • 5
  • 19

1 Answers1

1

We have a few issues:

  1. We only want to strftime once we have the entire date resolved. For this reason we need parenthesis around our offset computation.
  2. MonthEnd(1) is not generally what we want to get the end of the current month. We want MonthEnd(0)
  3. The format string is missing /

All together it can look like:

import pandas as pd
from pandas.tseries.offsets import MonthEnd

month_year = input("Enter Full Month and Year: ")  # Ie September 2021
assess_date = (
        pd.to_datetime(month_year, format="%B %Y") + MonthEnd(0)
).strftime('%m/%d/%Y %H:%M')
print(assess_date)

Program input/ouptut:

Enter Full Month and Year: September 2021
09/30/2021 00:00

The difference between MonthEnd(1) and MonthEnd(0) is that if it is the last day of the month the result will be different:

pd.Timestamp('2021-09-30') + MonthEnd(1)  # 2021-10-31 00:00:00
pd.Timestamp('2021-09-30') + MonthEnd(0)  # 2021-09-30 00:00:00
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Thanks, do you know how to strip that `0` before the `09`? – Jonnyboi Oct 19 '21 at 17:33
  • 1
    Add `#` or `-` before the Month pattern depending on operating system. For windows (`'%#m/%d/%Y %H:%M'`) or for linux/mac (`'%-m/%d/%Y %H:%M'`) [more details here](https://stackoverflow.com/a/42709606/15497888) – Henry Ecker Oct 19 '21 at 17:46