Skip to content Skip to sidebar Skip to footer

Converting Month Number To Datetime In Pandas

How do I transform a month number (float) to datetime in pandas with a format like 2010-01-01? date 0 1.0 1 2.0 2 3.0 3 4.0 4 5.0 Expect

Solution 1:

Append year and month and convert to date time

pd.to_datetime('2010-' + df.date.astype(int).astype(str) + '-1', format = '%Y-%m')

0   2010-01-01
1   2010-02-01
2   2010-03-01
3   2010-04-01
4   2010-05-01

Solution 2:

A simple solution can be to just add the year and day columns to the data frame, and call pd.to_datetime(df):

df = df.assign(year=2010, day=1, month=lambda l: l.date.apply(np.int)).drop('date', axis=1)
df['date'] = pd.to_datetime(df)

df = df.drop(['year', 'month', 'day'], axis=1)

print(df)

        date
0 2010-01-01
1 2010-02-01
2 2010-03-01
3 2010-04-01
4 2010-05-01

Post a Comment for "Converting Month Number To Datetime In Pandas"