Sajad Zarei
Sajad Zarei

Reputation: 43

convert Timestamps to month-year

How do I convert the timestamps to month-year.i.e. 9/5/2019 to Sep-2019.
I tried this but I'm getting array. here is what i did.

pd.DatetimeIndex(data['Timestamp']).year

pd.DatetimeIndex(data['Timestamp']).date

In this case I get arrays that I can append them together. But I'm looking for more efficient and also get letter month like 'Sep' instead of 9.

Thanks

Upvotes: 1

Views: 9845

Answers (2)

Locke Donohoe
Locke Donohoe

Reputation: 492

The method I use for formatting datetimes in my application uses the datetime.datetime module.
I use the datetime.strftime() function to get a formatted string from a datetime object

Code:

from datetime import datetime

timestamp = datetime.now()
pretty_date = datetime.strftime(timestamp, '%d/%b/%y')
print(pretty_date)

Output:

18/Nov/19

The exact same method can be used for date objects.

Code:

from datetime import date

timestamp = date.today()
pretty_date = date.strftime(timestamp, '%d/%b/%y')
print(pretty_date)

Output:

18/Nov/19

For a list of format codes for the strptime and strftime functions, they can be found in the python docs for datetime

Upvotes: 2

oppressionslayer
oppressionslayer

Reputation: 7224

You can convert your datetime format your using like this:

$ cat newdate.csv 
Name,Date
Will,9/5/2019
Bill,11/5/2019

df=pd.read_csv('newdate.csv')
df['Date']=pd.to_datetime(df['Date']).dt.strftime('%b-%Y') 

#In [323]: df                                                                                                                                                                                           
#Out[323]: 
#   Name      Date
#0  Will  Sep-2019
#1  Bill  Nov-2019

You may be able to use this next line directly if you update the column name

df['Date']=pd.to_datetime(df['Date']).dt.strftime('%b-%Y') 

so if you date column has a name other than 'Date', just change it to your column name

Upvotes: 1

Related Questions