Python | time.localtime() method
Last Updated :
14 Apr, 2025
Improve
Time module in Python provides handy tools to work with time-related tasks. One of its most useful functions is time.localtime(), which converts time expressed in seconds since the epoch (January 1, 1970) into a local time representation. It returns a time.struct_time object, which is a tuple-like structure containing detailed components like year, month, day, hour, etc. If no time is passed, time.localtime() returns the current local time.
Here's what the returned object contains:
Index | Attribute | Description |
---|---|---|
0 | tm_year | Year (e.g., 2025) |
1 | tm_mon | Month (1–12) |
2 | tm_mday | Day of the month (1–31) |
3 | tm_hour | Hour (0–23) |
4 | tm_min | Minute (0–59) |
5 | tm_sec | Second (0–61, includes leap sec) |
6 | tm_wday | Weekday (0–6, Monday is 0) |
7 | tm_yday | Day of the year (1–366) |
8 | tm_isdst | Daylight Saving (0, 1, or -1) |
Syntax
time.localtime([secs])
Parameter:
- secs (optional): Number of seconds since the epoch. If omitted or None, the current time is used.
Return type: object of class 'time.struct_time'.
Examples of time.localtime() Mehod
Example 1: Get current local time
import time
obj = time.localtime()
print(obj)
print(time.asctime(obj))
Output
time.struct_time(tm_year=2025, tm_mon=4, tm_mday=12, tm_hour=11, tm_min=38, tm_sec=10, tm_wday=5, tm_yday=102, tm_isdst=0) Sat Apr 12 11:38:10 2025
Explanation:
- time.localtime() gives you the current time broken down into its parts.
- time.asctime() converts the struct_time into a readable string like "Thu Apr 10 16:35:12 2025".
Example 2: Convert specific time (in seconds) to local time
import time
secs = 950000000
obj = time.localtime(secs)
print("Local time for seconds =", secs)
print(obj)
Output
Local time for seconds = 950000000 time.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=8, tm_min=53, tm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0)
Explanation:
- Here, 950000000 represents a specific point in time.
- time.localtime(secs) converts it to a full struct_time format based on your local timezone.
Example 3: What happens with fractional seconds?
import time
# Time with fractional seconds
secs = 950000000.81956
obj = time.localtime(secs)
print("Local time for seconds =", secs)
print(obj)
Output
Local time for seconds = 950000000.81956 time.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=8, tm_min=53, tm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0)
Explanation:
- Although we passed a float (950000000.81956), the fractional part is ignored.
- We'll get the same result as if you passed 950000000 as an integer.
Reference:https://docs.python.org/3/library/time.html#time.localtime