6

I have a DataFrame with epoch timestamp and I want to create a new column with a formatted date string.

index   timestamp
0       1456407930
1       1456407945
2       1456407961
3       1456407977
4       1456407992
5       1456408008
6       1456408024
7       1456408040
8       1456408055
9       1456408071
10      1456408087
11      1456408102

First, I successfully convert the timestamp to datetime format using

data['date_num'] = mdate.epoch2num(data['timestamp'])

But I didn't find a function to get a new column with a string formatted date (such as “%Y-%m-%d”).

I would appreciate any ideas? Patricio

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 1
    `df.timestamp=pd.to_datetime(df.timestamp,unit='s').dt.date `https://stackoverflow.com/questions/19231871/convert-unix-time-to-readable-date-in-pandas-dataframe – BENY May 03 '18 at 21:43

2 Answers2

7

Specify unit='s' with pd.to_datetime. Then use pd.Series.dt.strftime.

df['date'] = pd.to_datetime(df['timestamp'], unit='s')\
               .dt.strftime('%Y-%m-%d')

print(df)

    index   timestamp        date
0       0  1456407930  2016-02-25
1       1  1456407945  2016-02-25
2       2  1456407961  2016-02-25
3       3  1456407977  2016-02-25
4       4  1456407992  2016-02-25
5       5  1456408008  2016-02-25
6       6  1456408024  2016-02-25
7       7  1456408040  2016-02-25
8       8  1456408055  2016-02-25
9       9  1456408071  2016-02-25
10     10  1456408087  2016-02-25
11     11  1456408102  2016-02-25
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Simple, beatiful solution and upvote. I know the feeling when write a correct answer and nobody upvote it in order to recognize the invested time and effort into answering it. – Mihai Alexandru-Ionut May 04 '18 at 09:24
  • 1
    @MihaiAlexandru-Ionut, Thks, yours is acceptable too :) – jpp May 04 '18 at 09:26
2

You can use map method by passing a lambda expression as argument.

df['new_column'] = df['timestamp'].map(lambda val: datetime.datetime.fromtimestamp(val).strftime('%Y-%m-%d'))

Output

    timestamp  new_column
0  1456407930  2016-02-25
1  1456407945  2016-02-25
-------------------------
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128