PeterL
PeterL

Reputation: 515

Converting date using to_datetime

I am still quite new to Python, so please excuse my basic question.

After a reset of pandas grouped dataframe, I get the following:

    year    month   pl
0   2010    1   27.4376
1   2010    2   29.2314
2   2010    3   33.5714
3   2010    4   37.2986
4   2010    5   36.6971
5   2010    6   35.9329

I would like to merge year and month to one column in pandas datetime format.

I am trying:

C3['date']=pandas.to_datetime(C3.year + C3.month, format='%Y-%m')

But it gives me a date like this:

    year    month   pl  date
0   2010    1   27.4376 1970-01-01 00:00:00.000002011

What is the correct way? Thank you.

Upvotes: 2

Views: 70

Answers (1)

EdChum
EdChum

Reputation: 393883

You need to convert to str if necessary, then zfill the month col and pass this with a valid format to to_datetime:

In [303]:
df['date'] = pd.to_datetime(df['year'].astype(str) + df['month'].astype(str).str.zfill(2), format='%Y%m')
df

Out[303]:
   year  month       pl       date
0  2010      1  27.4376 2010-01-01
1  2010      2  29.2314 2010-02-01
2  2010      3  33.5714 2010-03-01
3  2010      4  37.2986 2010-04-01
4  2010      5  36.6971 2010-05-01
5  2010      6  35.9329 2010-06-01

If the conversion is unnecessary then the following should work:

df['date'] = pd.to_datetime(df['year'] + df['month'].str.zfill(2), format='%Y%m')

Your attempt failed as it treated the value as epoch time:

In [305]:
pd.to_datetime(20101, format='%Y-%m')

Out[305]:
Timestamp('1970-01-01 00:00:00.000020101')

Upvotes: 1

Related Questions