Skip to content

Convert Timestamp to DateTime for Pandas DataFrame

August 8th, 2017 - SoftwareTutorial(1 min)

To convert a pandas data frame value from unix timestamp to python datetime you need to use:

pd.to_datetime(df['timestamp'], unit='s')

where:

  • timestamp is the column containing the timestamp value
  • unit='s' defines the unit of the timestamp (seconds in this case)

You can actually replace the column altogether:

df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')

Unfortunately, the conversion is not really aware of the time zone so, if you want to e.g. create a django module, you’ll need to make the datetime object aware:

df.timestamp = df.timestamp.dt.tz_localize('UTC')

Moreover, if you want to change to another timezone, you’ll need to:

df.rimestamp.dt.tz_localize('UTC').dt.tz_convert('Europe/Brussels')

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: