首页 > 解决方案 > 如何将 pandas Period 转换为时间戳或日期时间对象?

问题描述

我有一个存储为 Pandas Period 对象的日期:

date1 = Period(1989, 'Y')

我想将它与 datetime 对象进行比较,即:

date2 = datetime.strftime('1988-09-09', '%Y-%m-%d')

我希望我可以做如下减法:

diff = date2 - date1

为此,我需要将 Period 转换为 datetime 对象。有没有办法做到这一点?

标签: pythonpandas

解决方案


  • 通过使用pandas.Period.to_timestamp
    • 使用freq参数指定开始或结束
  • date2 = datetime.strftime('1988-09-09', '%Y-%m-%d')导致TypeError
    • 用于date2 = pd.to_datetime('1988-09-09')获取日期时间格式
import pandas as pd

date1 = pd.Period(1989, 'Y')

date1_ts = date1.to_timestamp()

print(date1_ts)
[out]:
Timestamp('1989-01-01 00:00:00')

# create date2 as a datetime, not a string
date2 = pd.to_datetime('1988-09-09')

# take the difference
diff = date2 - date1_ts

print(diff)
[out]: 
Timedelta('-114 days +00:00:00')

推荐阅读