marlon
marlon

Reputation: 7653

How can I convert a pandas Period into a timestamp or datetime object?

I have a date stored as a Pandas Period object:

date1 = Period(1989, 'Y')

I want to compare it with a datetime object, which is:

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

I hope I can do a subtraction like below:

diff = date2 - date1

In order to do that, I need to convert the Period into a datetime object. Is there a way to do that?

Upvotes: 1

Views: 4153

Answers (2)

Trenton McKinney
Trenton McKinney

Reputation: 62413

  • By using pandas.Period.to_timestamp
    • Use the freq parameter to specify start or end
  • date2 = datetime.strftime('1988-09-09', '%Y-%m-%d') causes a TypeError
    • Use date2 = pd.to_datetime('1988-09-09') to get a datetime format
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')

Upvotes: 1

Ahx
Ahx

Reputation: 7985

Maybe you could do:

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') gave error, therefore I replaced with

date2 = datetime.now().strftime('%Y-%m-%d').split('-')[0]

Output:

31

Upvotes: 0

Related Questions