Galileo
Galileo

Reputation: 321

Transform a timestamp to a date with "%m/%Y" format

What is the best way to transform a timestamp (for instance: 2015-07-01 00:00:00) to a date with the following format "03/2017" in Python 3?

Upvotes: 0

Views: 47

Answers (2)

jpp
jpp

Reputation: 164753

You can do this with pd.Series.dt.strftime:

import pandas as pd

s = pd.Series(pd.date_range(pd.Timestamp('now'), periods=2))

# 0   2018-03-31 22:57:30.819192
# 1   2018-04-01 22:57:30.819192
# dtype: datetime64[ns]

res = s.dt.strftime('%m/%Y')

# 0    03/2018
# 1    04/2018
# dtype: object

Upvotes: 0

AmiNadimi
AmiNadimi

Reputation: 5725

If I understand correctly, by timestamp you might mean a variable of datetime type. (considering your example)

The datetime class has a method strftime. strftime() is the method you are looking for.

For this specific example, it would look something like:

your_datetime.strftime("%m / %Y")

for more information read the docs.

If by timestamp you really mean a posix epoch time which you want to convert, your code would look like :

datetime.datetime.utcfromtimestamp(your_datetime).strftime("%m / %Y")

And also your import statement should be :

import datetime

Upvotes: 1

Related Questions