Python datetime to integer timestamp
In this article, we are going to see how to convert python DateTime to integer timestamp.
The timestamp() function returns the time expressed as the number of seconds that have passed since January 1, 1970. That zero moment is known as the epoch. First, we will get the current time or explicitly mention the required date and time we want the timestamp of. There are several ways to get the date and time. We will see them as we go through the examples. Then we will convert the datetime into timestamp using timestamp() function.
At last, we will round off the timestamp in seconds and milliseconds and explicitly typecast into integer datatype and our work is done!
Example 1: Integer timestamp of the current date and time
Here we import the DateTime module to use the DateTime function from it. And then use datetime.now() function to get the current date and time. Convert the DateTime object into timestamp using DateTime.timestamp() method. We will get the timestamp in seconds. And then round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds.
Current datetime: 2021-08-25 15:04:33.794484 Integer timestamp of current datetime: 1629884074
Example 2: Integer timestamp of specified date and time
Give the date and time as parameters inside the datetime() function. Convert the datetime object into timestamp using datetime.timestamp() method. We will get the timestamp in seconds. Round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds. We can also convert it into milliseconds by multiplying it by1000 to get the integer timestamp in milliseconds.
Datetime: 2018-01-01 20:00:00 Integer timestamp in seconds: 1514817000 Integer timestamp in milliseconds: 1514817000000
Example 3: UTC(Universal Time Coordinated) integer timestamp using calendar.timegm
First, we enter the UTIC time inside the datetime.datetime() object. Then we pass the object to d.timtuple() function which gives a tuple containing the parameters like year, month, day, and so on, and then using the calendar function we convert the datetime to integer UTC timestamp.
Timestamp in integer since epoch: 7260
Example 4: Particular timezone integer timestamp
First, we get the current time using datetime.datetime.now(). And then import the pytz library to instantiate the timezone object to localize the datetime. Convert the datetime object into timestamp using datetime.timestamp() method. We will get the timestamp in seconds. Round off and convert the timestamp in integer to get the integer timestamp.
Time Zone: Asia/Kolkata Datetime: 2021-08-25 15:09:05.194413+05:30 Integer timestamp: 1629884345