Convert DateTime to Integer in Python

Python provides developers with many robust tools. Among them, several tools work with dates and times. In this article, we will talk about the datetime and time modules. We will study how they work. Let's start with the datetime!

datetime enables us to identify and process time-related elements, such as dates, hours, minutes, seconds, days of the week, months, years, and so on. It provides us with various services like managing time zones and daylight savings time. Moreover, datetime can work with timestamp data and it can extract the day of the week, day of the month, and other date and time formats from strings.

In short, datetime is a really useful way of handling anything date and time-related in Python. So let's see how to convert DataTime to integer in Python!

How to Convert DateTime to Integer in Python

Using the time module, you can get the current time in milliseconds in Python. And you can get the time in seconds using time.time function. To convert it to milliseconds, you should multiply it by 1000 and round it off. Please see an example below.

import time
milliseconds = int(round(time.time() * 1000))

Let's say you may want to convert a datetime object to a milliseconds timestamp. Then, you should use the timestamp function and use the same math as above to get the milliseconds time.

import time
from datetime import datetime
dt = datetime(2021, 1, 1)
milliseconds = int(round(dt.timestamp() * 1000))

Leave a reply