Home > Back-end >  Pandas datetime, converting monthly date to month end day
Pandas datetime, converting monthly date to month end day

Time:10-20

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')

CodePudding user response:

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
  • Related