在 Python / SQL Server / Stata 上以天为单位计算 datediff

Calculating datediff in days on Python / SQL Server / Stata

我想创建一个名为天数的新列来计算每个不同用户的日期差异。

例如,不同用户 x1 的天数从 x1 的最小日期开始,天数看起来像..

天 = 1, 2,3,4,5,6,...

对数据中的每个不同用户执行此操作的最佳方法是什么?

每个不同的用户在数据集中有不同的日期长度,如图所示。

任何使用 SQL 服务器、Python 或 Stata 的解决方案?

提前致谢。

这是一个 Stata 解决方案,假设您将日期作为字符串导入:

* GENERATE SAMPLE DATA
    clear
    set obs 2
    gen user_i = _n
    expand 10
    gen month = runiformint(1,12)
    gen day = runiformint(1,28) if inlist(month,2)
    replace day = runiformint(1,31) if inlist(month,1,3,5,7,8,10,12)
    replace day = runiformint(1,30) if mi(day)
    gen e_date = "2019" + "-" + (2 - strlen(string(month)))*"0" + string(month) + "-" + (2 - strlen(string(day)))*"0" + string(day)
    drop month day

* calculate days
    gen date = date(e_date, "YMD")
    format date %td
    bysort user_i (date): gen days_from_min = date-date[1]

话虽这么说,但肯定有一种方法可以在 MSSQL 或当前存放数据的任何地方轻松完成此操作。