showkey
showkey

Reputation: 358

How can convert string to date which only contains year number?

Create a dataframe whose first column is a text.

import pandas as pd
values = {'dates':  ['2019','2020','2021'],
          'price': [11,12,13]
          }
df = pd.DataFrame(values, columns = ['dates','price'])

Check the dtypes:

df.dtypes
dates    object
price     int64
dtype: object

Convert type in the column dates to type dates.

df['dates'] = pd.to_datetime(df['dates'], format='%Y')
df
       dates  price
0 2019-01-01     11
1 2020-01-01     12
2 2021-01-01     13

I want to convert the type in dates column to date and the dates in the following format----contains only year number:

    dates  price
0 2019     11
1 2020     12
2 2021     13

How can achieve the target?

Upvotes: 0

Views: 746

Answers (1)

mozway
mozway

Reputation: 260620

If you choose to have the datetime format for your columns, it is likely to benefit from it. What you see in the column ("2019-01-01") is a representation of the datetime object. The realquestion here is, why do you need to have a datetime object?

Actually, I don't care about datetime type:

Use a string ('2019'), or preferentially an integer (2019) which will enable you to perform sorting, calculations, etc.

I need the datetime type but I really want to see only the year:

Use style to format your column while retaining the underlying type:

df.style.format({'dates': lambda t: t.strftime('%Y')})

This will allow you to keep the type while having a clean visual format

Upvotes: 1

Related Questions