簡體   English   中英

從 python 中的日期轉換的一天、一周和一個月的分數

[英]Fraction of a day, of a week and of a month conversion from date in python

我有這個 pandas dataframe 次:

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 中的這個問題嗎? 任何幫助將不勝感激。

嘗試:

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

您會發現很多對時間和日期時間函數的內置支持

首先確保您的df['time']列正確存儲為日期時間,然后以下應該可以解決問題:


# get number of seconds elapsed in the day - total seconds in a day
# note here we create a timedelta
# hack: use df['time'].dt.date to set time to 00:00:00
df['frac_day'] = (df['time'] - pd.to_datetime(df['time'].dt.date)).dt.total_seconds() / (24 * 3600)

df['frac_week'] = (df['time'].dt.dayofweek + df['frac_day']) / 7

df['frac_month'] = (df['time'].dt.day + df['frac_day'] - 1)/ df['time'].dt.days_in_month 

df

另一種解決方案:

df["frac_day"] = (
    df["time"].dt.hour * 60 * 60
    + df["time"].dt.minute * 60
    + df["time"].dt.second
) / (24 * 60 * 60)

df["frac_week"] = (df["time"].dt.dayofweek + df["frac_day"]) / 7
df["frac_month"] = df["time"].apply(lambda x: pd.Period(str(x)).days_in_month)
df["frac_month"] = ((df["time"].dt.day - 1) / df["frac_month"]) + df[
    "frac_day"
] / df["frac_month"]
print(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM