I have a value in milliseconds in a Python program. For example: 1557975599999

And I would like to convert it to a string with days and hours, minutes, seconds. How can I do this?

1

2 Answers

To convert unix timestamp to datetime, you can use datetime.fromtimestamp(). The only problem, that your timestamp is in miliseconds, but function expect timestamp in seconds. To cut miliseconds you can divide timestamp to 1000.

Code:

from datetime import datetime a = 1557975599999 date = datetime.fromtimestamp(a // 1000) print(date) 

Output:

2019-05-16 05:59:59 

Upd.

@Daniel in comments noticed that fromtimestamp() accept floats, so we can save miliseconds from original timestamp. All we need is just to remove one symbol :D

date = datetime.fromtimestamp(a / 1000) 
0

With Pandas’ to_datetime()

import pandas as pd pd.to_datetime(a, unit='ms') # Or with a dataframe(column): df['date'] = pd.to_datetime(df['Millisecond_time'], unit='ms') 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.