我想修改熊猫时间戳变量的日期,但保持时间不变。例如具有以下时间戳
time_stamp_1 = pd.Timestamp('1900-1-1 13:59')
我想把日期定在2000年2月3日。即修改后的打印语句
print(time_stamp_1)
应该回来
2000-02-03 13:59:00
发布于 2019-09-20 05:16:50
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
发布于 2019-09-20 05:24:50
也可以做到:
new = pd.Timestamp('2000-02-03') + pd.Timedelta(str(time_stamp_1.time()))
产出:
Timestamp('2000-02-03 13:59:00')
发布于 2019-09-20 07:01:03
您可以使用normalize
进行减法
pd.to_datetime('2000-02-03') + (time_stamp_1 - time_stamp_1.normalize())
Timestamp('2000-02-03 13:59:00')
如果您有一个Series/DataFrame,它的扩展性要好得多,因为它避免了.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)"
)
https://stackoverflow.com/questions/58029124
复制