Home > Blockchain >  Extract day from a pandas Timestamp
Extract day from a pandas Timestamp

Time:10-16

Goal

I would like to extract the day (i.e."2022-10-10") from a pandas Timestamp - in the local timezone if possible.

Example

from pandas import Timestamp
t = Timestamp('2022-10-10 06:00:00 0000', tz='UTC', freq='15T')

What I have tried

import datetime
datetime.datetime.strptime(str(t), '%Y-%m-%d %H:%M:%S')

Issue:

ValueError: unconverted data remains: 00:00

CodePudding user response:

I think this is what you're trying to accomplish:

from pandas import Timestamp
t = Timestamp('2022-10-10 06:00:00 0000', tz='UTC', freq='15T')
# get date object from timestamp
date = t.date()
# format date to string
date_str = date.strftime('%Y-%m-%d')

CodePudding user response:

Just call the t.to_pydatetime(). It returns datetime object.

t = Timestamp('2022-10-10 06:00:00 0000', tz='UTC', freq='15T')

t.to_pydatetime()
>> datetime.datetime(2022, 10, 10, 6, 0, tzinfo=<UTC>)

t.to_pydatetime().year
>> 2022

t.to_pydatetime().month
>> 10

t.to_pydatetime().day
>> 10
  • Related