-4

I have a pandas Series that is of the following format

dates = [Nov 2022, Dec 2022, Jan 2023, Feb 2023 ..]

I want to create a dataframe that takes these values and has the number of days. I have to consider of course the case if it is a leap year

I have created a small function that splits the dates into 2 dataframes and 2 lists of months depending if they have 30 or 31 days like the following
month = [Nov, Dec, Jan, Feb ..] and
year = [2022, 2022, 2023, 2023 ..] and then use the isin function in a sense if the month is in listA then insert 31 days etc. I also check for the leap years. However, I was wondering if there is a way to automate this whole proces with the pd.datetime

  • 1
    How do you "take these values" and have a "number of days" ? Quite unclear. – 0x0fba Nov 22 '22 at 12:49
  • What have you tried and what is expected result? Also check [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/4046632). Note, `dates` is not valid list right now. – buran Nov 22 '22 at 12:49
  • Check https://stackoverflow.com/q/28819470/4046632 – buran Nov 22 '22 at 12:53

1 Answers1

0

If you want the number of days in this month:

dates = pd.Series(['Nov 2022', 'Dec 2022', 'Jan 2023', 'Feb 2023'])

out = (pd.to_datetime(dates, format='%b %Y')
         .dt.days_in_month
      )

# Or

out = (pd.to_datetime(dates, format='%b %Y')
         .add(pd.offsets.MonthEnd(0))
         .dt.day
      )

Output:

0    30
1    31
2    31
3    28
dtype: int64

previous interpretation

If I understand correctly, you want the day of year?

Assuming:

dates = pd.Series(['Nov 2022', 'Dec 2022', 'Jan 2023', 'Feb 2023'])

You can use:

pd.to_datetime(dates, format='%b %Y').dt.dayofyear

NB. The reference is the start of each month.

Output:

0    305
1    335
2      1
3     32
dtype: int64
mozway
  • 194,879
  • 13
  • 39
  • 75
  • It looks they want the number of days in the month, but it's not clear – buran Nov 22 '22 at 12:51
  • Hey, Thank you for the feedback. Not exactly, I want the days of each month. So in this case it should be [30, 31, 31. 28, ... etc ] – papsmilpet Nov 22 '22 at 12:51
  • There is https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.days_in_month.html I have added link to duplicate, but already voted to close as need details or clarity – buran Nov 22 '22 at 12:55