【问题标题】:Python: Rounding timstamp to 15min interval, appended to a df but missing hours, minutes and seconds, dtype: datetime64[ns]Python:将时间戳舍入到 15 分钟间隔,附加到 df 但缺少小时、分钟和秒,dtype:datetime64[ns]
【发布时间】:2023-03-16 23:33:01
【问题描述】:

当我将时间戳四舍五入到最近的 15 分钟并附加回数据帧时,我遇到了一个问题,HMS 不会出现,只显示日期。我该如何解决?

原始数据集:

        uid timestamp           loc app_id  traffic
2807379 941 2016-04-20 00:00:00 6049    2   0.001
2817702 942 2016-04-20 00:00:03 9803    350 0.001
2817701 942 2016-04-20 00:00:03 6406    15  0.000
424540  325 2016-04-20 00:00:03 2654    127 0.001

四舍五入到最近的 15 分钟间隔:

round_15_min = usage["timestamp"].dt.round("15min")

打印出round_15_min:

2807379   2016-04-20 00:00:00
2817702   2016-04-20 00:00:00
2817701   2016-04-20 00:00:00
424540    2016-04-20 00:00:00

但是,当附加回原始数据集时,它变成了:

        uid timestamp           loc app_id  traffic rounded_timestamp
2807379 941 2016-04-20 00:00:00 6049    2   0.001   2016-04-20
2817702 942 2016-04-20 00:00:03 9803    350 0.001   2016-04-20
2817701 942 2016-04-20 00:00:03 6406    15  0.000   2016-04-20
424540  325 2016-04-20 00:00:03 2654    127 0.001   2016-04-20

来自datetime64[ns] 的dtype 变成了dtype('

【问题讨论】:

标签: python pandas datetime


【解决方案1】:

您可以使用Datetime 库:


import datetime
usage["timestamp"] = usage["timestamp"].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,15*(dt.minute // 15)))

例如,

        id                  dt
0  2807379 2016-04-20 00:00:00
1  2817702 2016-04-20 00:33:03
2  2817701 2016-04-20 00:09:03
3   424540 2016-04-20 00:50:03

会变成:

        id                  dt
0  2807379 2016-04-20 00:00:00
1  2817702 2016-04-20 00:30:00
2  2817701 2016-04-20 00:00:00
3   424540 2016-04-20 00:45:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多