How to Convert Milliseconds to Date and Time Format?

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

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.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest