Ask Your Question
4

What is the method of generating a Python datetime object from milliseconds?

asked 2022-10-03 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-05-01 18:00:00 +0000

ladyg gravatar image

To generate a Python datetime object from milliseconds, you can use the datetime.fromtimestamp() method. However, since the fromtimestamp() method takes seconds as input, you need to divide the milliseconds by 1000 first. Here is an example:

import datetime

milliseconds = 1578744600387
seconds = milliseconds / 1000.0
dt = datetime.datetime.fromtimestamp(seconds)

print(dt)

Output:

2020-01-11 18:50:00.387000

Alternatively, you can use the datetime.utcfromtimestamp() method if you want the datetime object to be in UTC timezone:

import datetime

milliseconds = 1578744600387
seconds = milliseconds / 1000.0
dt = datetime.datetime.utcfromtimestamp(seconds)

print(dt)

Output:

2020-01-11 11:50:00.387000
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-03 11:00:00 +0000

Seen: 12 times

Last updated: May 01 '22