Home > Software engineering >  Is there a way to extract hours per month from a datetime object?
Is there a way to extract hours per month from a datetime object?

Time:01-06

I have a datetime column of elements which are something like 2010-05-31 00:00:00 and continue for various months. I want to find a way to extract the hours per month for each datetime object as I have another column I want to divide by the hours per month. Is there a way to do this cleanly?

The values are between a couple of months like this:

Time                 Value
2000-01-02 00:00:00  200
2000-01-03 00:00:00  300
...

I would want another column that is basically Value/total hours per month for Time so for january it would be 200/744, 300/744 (31 days=744 hours) etc and this continues for feb, march etc.

CodePudding user response:

pandas comes with all you need; use .days_in_month and multiply by 24 to get hours, e.g.

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

df['hours_in_month'] = df['Time'].dt.days_in_month * 24

print(df)
        Time  Value  hours_in_month
0 2000-01-02    200             744
1 2000-01-03    300             744
2 2000-02-01    400             696
  •  Tags:  
  • Related