首页 > 解决方案 > 从python中的日期转换的一天、一周和一个月的分数

问题描述

我有这个熊猫数据框:

id    time
1     4/01/2019 08:00:00
2     4/02/2019 12:00:00
3     4/03/2019 18:00:00

我想要一天的一部分,一周的一部分和一个月的一部分。例如,第一行 08:00:00 是一天的三分之一,所以第一列应该是 0.333。这是星期一,所以它应该是 0.047(完整的一天是一周的 1/7 = 0.143,但因为它是第三天,所以 0.143 * 0.333 = 0.047)。这是月初,所以它应该是 0.011(完整的一天是一个月的 1/30 = 0.033,但它只是上午 8 点,所以它是 0.033 * 0.333 = 0.011。

请注意,这些值是针对完整天数的,例如 4/02/2019 12:00:00,仅计算 1 天半。

预期的结果应该是:

id    time                 frac_day    frac_week    frac_month
1     4/01/2019 08:00:00   0.333       0.047        0.011
2     4/02/2019 12:00:00   0.5         0.214        0.050
3     4/03/2019 18:00:00   0.75        0.393        0.092    

拜托,你能在python中帮我解决这个问题吗?任何帮助将不胜感激。

标签: pythonpandas

解决方案


尝试:

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

df = pd.DataFrame({
    'id': [1, 2, 3],
    'time': ['4/01/2019 08:00:00', '4/02/2019 12:00:00',
             '4/03/2019 18:00:00']
})

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

# Percentage of Day by dividing current hour by number of hours in day
df['frac_day'] = df['time'].dt.hour / 24

# Get midnight the beginning of the week for each row
beginning_of_each_week = (
        df['time'] - pd.to_timedelta(df['time'].dt.dayofweek, unit='D')
).dt.normalize()
seconds_in_week = 24 * 7 * 60 * 60

# % of week so far. by dividing total seconds by total seconds in week
df['frac_week'] = (
                          df['time'] - beginning_of_each_week
                  ).dt.total_seconds() / seconds_in_week

# Get Timedelta based on midnight of the first day of the current month
time_so_far = df['time'] - (df['time'] - MonthEnd(1) + Day(1)).dt.normalize()
# Get Total time for the given month
time_in_month = (df['time'] + MonthEnd(1)) - (df['time'] - MonthEnd(1))

# % of month so far by dividing values
df['frac_month'] = time_so_far / time_in_month

df

   id                time  frac_day  frac_week  frac_month
0   1 2019-04-01 08:00:00  0.333333   0.047619    0.011111
1   2 2019-04-02 12:00:00  0.500000   0.214286    0.050000
2   3 2019-04-03 18:00:00  0.750000   0.392857    0.091667

推荐阅读