我有一个存储为Pandas Period对象的日期:
date1 = Period(1989, 'Y')
我想将它与日期时间对象进行比较,该对象是:
date2 = datetime.strftime('1988-09-09', '%Y-%m-%d')
我希望可以进行如下减法运算:
diff = date2 - date1
为此,我需要将Period转换为datetime对象。有办法吗?
答案 0 :(得分:1)
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')
答案 1 :(得分:0)
也许您可以做到:
from datetime import datetime
from pandas import DataFrame, Period
if __name__ == '__main__':
data = {'Year': [Period(1989, 'Y')]}
df = DataFrame(data,
columns=['Year'])
date2 = datetime.now().strftime('%Y-%m-%d').split('-')[0]
date1 = df['Year'].values[0].year
diff = int(date2) - date1
print(diff)
date2 = datetime.strftime('1988-09-09', '%Y-%m-%d')
输入了错误,因此我替换为
date2 = datetime.now().strftime('%Y-%m-%d').split('-')[0]
输出:
31