Python .mktime()
In the time module, the .mktime() function takes a struct_time object or a 9-element tuple representing local time and returns a floating-point number of seconds since the epoch (i.e., “Unix timestamp” in local time). It is effectively the inverse of time.localtime().
Syntax
time.mktime(t)
Parameters:
t: Atime.struct_timeobject or a full 9-element tuple ((year, month, day, hour, minute, second, weekday, day_of_year, isdst)) representing local time.
Return value:
A float representing seconds since the epoch in local time. Raises OverflowError or ValueError if the input cannot be represented.
Example 1: Basic conversion from tuple to timestamp
This example converts a local time tuple directly into seconds since epoch:
import timetime_tuple = (2025, 4, 11, 14, 30, 0, 4, 101, -1) # year, month, day, hour, minute, second, weekday, yearday, isdsttimestamp = time.mktime(time_tuple)print("Timestamp:", timestamp)
The output of this code can be:
Timestamp: 1744381800.0
Note: The exact timestamp value depends on system’s local timezone. The value shown represents the result in UTC. In other timezones, the output will differ by the timezone offset.
Example 2: Convert current local time (via struct_time) to timestamp
This example gets the current local time in struct_time form and then uses .mktime() to convert it to an epoch seconds value:
import timelocal_struct = time.localtime()timestamp = time.mktime(local_struct)print("Current local seconds since epoch:", timestamp)
A possible output of this code is:
Current local seconds since epoch: 1762169287.0
Codebyte Example
This interactive example shows conversion and round-trip (timestamp ↔ struct_time) behaviour:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours