Reputation: 10626
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:
import datetime
df['TimeStamp']=datetime.datetime.fromtimestamp(df['TimeStamp'])
does not seem to be working.
Upvotes: 0
Views: 43
Reputation: 15738
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
Upvotes: 1