0

I currently have the following output:

df.Date

0        2020/2/29 12:40:0
1        2020/2/29 12:50:0
2         2020/2/29 13:0:0
3        2020/2/29 13:10:0
4        2020/2/29 13:20:0
...       
21525    2020/7/28 10:10:0
21526    2020/7/28 10:20:0
21527    2020/7/28 10:30:0
21528    2020/7/28 10:40:0
21529    2020/7/28 10:50:0
Name: Date, Length: 21530, dtype: object

And I would like to eliminate the year, hours, mins and secs, leaving just the month and day:

0        2/29
1        2/29
2        2/29
3        2/29
4        2/29
...
21525    7/28
21526    7/28

I tried to use the replace function, but it messed up my data somehow:

df.Date = df.Date.str.replace('2020/' , '')
df.Date = df.Date.str.replace('..:..:.' , '')

Is there other way to do this?

arevalo
  • 13
  • 3
  • 1
    try `strftime`: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html you can use this reference to figure out the formatting string: https://strftime.org/ – Dan Jul 29 '20 at 17:58
  • it looks like a date.... so `df.Date.dt.strftime("%m/%d")` – Rob Raymond Jul 29 '20 at 18:00
  • Does this answer your question? [How to change the datetime format in pandas](https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas) – sushanth Jul 29 '20 at 18:00

2 Answers2

1

Do the following:

df.date = pd.to_datetime(df.date)
df.date.dt.strftime("%m/%d")

The output is:

0    02/29
1    02/29
2    02/29
3    02/29
4    02/29
5    07/28
...
Roy2012
  • 11,755
  • 2
  • 22
  • 35
0
import pandas as pd
import numpy as np

dates = pd.date_range('2020-01-01', periods=500, freq='D')
df = pd.DataFrame({ 'date' : dates})
df['month_day'] = df.date.apply(lambda x: f"{x.month}/{x.day}")
mujjiga
  • 16,186
  • 2
  • 33
  • 51