How to convert milliseconds to date and time format?

Viewed 6395

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?

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)

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')
Related