How to Use the Python time mktime() Method

Contents
In this article, you will learn how to use the Python time mktime() method.
Python time mktime() Method
The mktime() method in Python is used to convert a struct_time object representing a date and time to a Unix timestamp, which is the number of seconds since January 1, 1970, at 00:00:00 UTC. Here’s how you can use the mktime() method:
Import the time module:
import time
Create a struct_time object representing the date and time you want to convert. You can create a struct_time object using the strptime() method from the datetime module. For example, to create a struct_time object representing January 1, 2022, at 12:00:00 AM:
import datetime
dt = datetime.datetime(2022, 1, 1, 0, 0, 0)
struct_time = dt.timetuple()
Call the mktime() method and pass the struct_time object as an argument:
timestamp = time.mktime(struct_time)
The timestamp variable now contains the Unix timestamp representing January 1, 2022, at 12:00:00 AM. You can then use this timestamp for further processing, such as converting it to a human-readable date and time using the strftime() method.
Note that the mktime() method assumes that the struct_time object represents a local time, not UTC time. If you want to convert a UTC time to a Unix timestamp, you should use the calendar.timegm() method instead of mktime().