Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do you convert pandas data frame epoch values to readable datetime format

I have a data frame like this:

print(df)
Metric  TimeStamp       Value
cpu     1642039200000   4
cpu     1642042800000   3
cpu     1642046400000   5

I need to convert TimeStamp to readaable time stamp yearmonthdate hour:min:sec

I have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import datetime

df['TimeStamp']=datetime.datetime.fromtimestamp(df['TimeStamp'])

does not seem to be working.

>Solution :

datetime.datetime.fromtimestamp expects a single value. To work with series, use pandas’ methods:

pd.to_datetime(df['TimeStamp']*1000000, utc=True).dt.tz_convert('EST').dt.strftime("%Y-%m-%d")

Example:

df = pd.DataFrame({'ts': [1642039200000, 1642042800000, 1642046400000]}) 
df['ts'] = pd.to_datetime(df['ts']*1000000, utc=True).dt.tz_convert('EST')
df['ts']

Output:

0   2022-01-12 21:00:00-05:00
1   2022-01-12 22:00:00-05:00
2   2022-01-12 23:00:00-05:00
Name: ts, dtype: datetime64[ns, EST]

To get a specific string format, df['ts'].dt.strftime("%Y-%m-%d") will output:

0    2022-01-12
1    2022-01-12
2    2022-01-12
Name: ts, dtype: object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading