簡體   English   中英

計算從年/月開始到今天的天數

[英]Count days from beginning of year/month to today

假設我們有一個 dataframe (df):

opendate
2020-08-04
2018-06-24
2011-03-17
2019-11-20

我想做兩件事:

  1. 對於每個日期,計算從特定年份開始到該日期的天數
  2. 對於每個日期,計算從特定月份開始到該日期的天數

在 R 中,我可以通過以下代碼執行此操作:

Year_Month_Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "year")));
df = transform(df, Year_day_played = Year_Month_Diff(opendate, opendate));

Month_Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "month")));
df= transform(df, Month_day_played = Month_Diff(opendate, opendate));

對於 python 等效項的任何幫助將不勝感激。

月份非常簡單,只需調用.dt.day

對於年份的情況,您從同年的 1 月 1 日減去日期,然后計算天數。

假設opendate已經是Timestamp類型:

df['Days since BOM'] = df['opendate'].dt.day
df['Days since BOY'] = (df['opendate'] - (df['opendate'] - pd.tseries.offsets.YearBegin())).dt.days

感謝@ChrisA,對於 year 案例有一個更簡單的解決方案:

df['Days since BOY'] = df['opendate'].dt.dayofyear 

這不像其他答案那么簡單,但它也有效。

from time import mktime, strptime
from datetime import datetime, timedelta

date = '2020-05-05'
time_format = '%Y-%m-%d'

def string_to_date(string, time_format):
    string = string.split(' ')[0]
    struct = strptime(string, time_format)
    obj = datetime.fromtimestamp(mktime(struct))
    return obj

def get_start_of_month(date):
    month_day = date.day
    to_remove = timedelta(days=month_day-1)
    new_date = date - to_remove
    return new_date

def get_start_of_year(date):
    new_date = datetime(date.year, 1, 1)
    return new_date

def time_from_month(date):
    start = get_start_of_month(date)
    obj = date - start
    return obj.days

def time_from_year(date):
    start = get_start_of_year(date)
    obj = date - start
    return obj.days

print(time_from_month(obj))
print(time_from_year(obj))

暫無
暫無

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

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