python - 如何将 pandas Period 转换为时间戳或日期时间对象?
问题描述
我有一个存储为 Pandas Period 对象的日期:
date1 = Period(1989, 'Y')
我想将它与 datetime 对象进行比较,即:
date2 = datetime.strftime('1988-09-09', '%Y-%m-%d')
我希望我可以做如下减法:
diff = date2 - date1
为此,我需要将 Period 转换为 datetime 对象。有没有办法做到这一点?
解决方案
- 通过使用
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')
推荐阅读
- ios - 移出屏幕时,Tableview 部分标题未正确转换
- c - 多线程和套接字多路复用(池)
- python - 如何避免将 np.datetime64 添加到 numpy 数组时自动转换为日期时间?
- powershell - PowerShell Import-Csv 列的多个 CSV 连接
- c++ - c ++类模板防止成员函数中的隐式转换
- c# - ASP.NET Core 依赖注入问题
- ruby-on-rails - ActionView::Template::Error(未定义方法 `to_model' 为 true:TrueClass 为更新属性方法
- javascript - 如何在angularjs中自动填充输入字段?
- aws-lambda - lambda 冷启动时间随着代码大小/Python 导入而增加
- c++ - 为什么我的代码不能从 C++ 中的 10 位数字开始工作?