【问题标题】:Pandas timestamp: modifying date and keeping time熊猫时间戳:修改日期和保持时间
【发布时间】:2019-09-20 13:15:13
【问题描述】:

我想修改 pandas Timestamp 变量的日期,但保持时间不变。例如。具有以下时间戳

time_stamp_1 = pd.Timestamp('1900-1-1 13:59')

我想将日期设置为 2000 年 2 月 3 日。即修改后的打印语句

print(time_stamp_1)

应该返回

2000-02-03 13:59:00

【问题讨论】:

    标签: python pandas timestamp


    【解决方案1】:

    使用Timestamp.replace:

    print (time_stamp_1.replace(year=2000, month=2, day=3))
    2000-02-03 13:59:00
    

    或添加到Timestamp 仅转换为timedelta 的时间由Timestamp.strftime 提取:

    print (pd.Timestamp('2000-02-03') + pd.Timedelta(time_stamp_1.strftime('%H:%M:%S')))
    #alternative
    print (pd.Timestamp('2000-02-03') + pd.to_timedelta(time_stamp_1.strftime('%H:%M:%S')))
    2000-02-03 13:59:00
    

    【讨论】:

      【解决方案2】:

      还可以:

      new = pd.Timestamp('2000-02-03') + pd.Timedelta(str(time_stamp_1.time()))
      

      输出:

      Timestamp('2000-02-03 13:59:00')
      

      【讨论】:

        【解决方案3】:

        你可以用normalize做减法

        pd.to_datetime('2000-02-03') + (time_stamp_1 - time_stamp_1.normalize())
        Timestamp('2000-02-03 13:59:00')
        

        如果你有一个系列/数据帧,这会更好地扩展,因为它避免了.strftime,但对于单个时间戳来说速度较慢。

        import perfplot
        import pandas as pd
        
        perfplot.show(
            setup=lambda n: pd.Series([pd.Timestamp('1900-1-1 13:59')]*n), 
            kernels=[
                lambda s: pd.to_datetime('2000-02-03') + (s - s.dt.normalize()),
                lambda s: pd.Timestamp('2000-02-03') + pd.to_timedelta(s.dt.strftime('%H:%M:%S')),
            ],
            labels=["normalize", "strftime"],
            n_range=[2 ** k for k in range(16)],
            equality_check=None,  # Because datetime type
            xlabel="len(s)"
        )
        

        【讨论】:

          猜你喜欢
          • 2017-02-23
          • 2021-05-08
          • 2019-06-16
          • 1970-01-01
          • 2016-07-05
          • 2021-09-04
          • 1970-01-01
          相关资源
          最近更新 更多