SSV
SSV

Reputation: 139

I have a Pandas series with timestamps, is there a way to convert it to unique dates?

I have a Pandas Series that contains Timestamp data. I wish to perform forecasting using Pytorch Forecasting. Or any other method where I can get unique dates ('YYYY:MM:DD' format). I tried this and this, but didn't get what I wanted. Any help would be much appreciated. Thank you.

0     2022-03-20 00:16:00+00:00
1     2022-03-20 00:48:00+00:00
2     2022-03-20 01:31:00+00:00
3     2022-03-20 02:10:00+00:00
4     2022-03-20 02:30:00+00:00
5     2022-03-20 03:04:00+00:00
6     2022-03-20 04:24:00+00:00
7     2022-03-20 04:51:00+00:00
8     2022-03-20 05:21:00+00:00
9     2022-03-20 06:23:00+00:00

Upvotes: 1

Views: 407

Answers (1)

Kid Charlamagne
Kid Charlamagne

Reputation: 588

Convert to a datetime object. Then extract date. convert to string and find unique ones.

dates = ['2022-03-20 00:16:00+00:00',
         '2022-03-20 00:48:00+00:00',
         '2022-03-22 01:31:00+00:00',
         '2022-03-20 02:10:00+00:00',
         '2022-03-20 02:30:00+00:00',
         '2022-03-20 03:04:00+00:00',
         '2022-03-20 04:24:00+00:00',
         '2022-03-20 04:51:00+00:00',
         '2022-03-20 05:21:00+00:00',
         '2022-03-24 06:23:00+00:00']

import pandas as pd

# assuming your date is a pandas series (or a column)
datetimes = pd.Series(dates)

# convert to datetime object
datetimes = pd.to_datetime(datetimes)

# extract the date
dates = datetimes.dt.date

# get unique date
unique_dates = dates.astype(str).unique()

print(unique_dates)

The result is:

['2022-03-20' '2022-03-22' '2022-03-24']

Upvotes: 1

Related Questions