Overview The Python time module provides various functions for working with time. Related functionality can be found in the datetime and calendar modules.
While this module is available on all platforms, not all functions are supported across all platforms. Most functions in this module are implemented by calling the corresponding functions in the platform's C library. Because the semantics of these functions may vary between platforms, it's advisable to consult the relevant documentation for your specific platform.
Terminology Here are explanations of some key terms:
2.1 UTC UTC stands for Coordinated Universal Time. It was previously known as Greenwich Mean Time (GMT). The use of UTC instead of CUT as an abbreviation is a compromise between English (Coordinated Universal Time) and French (Temps Universel Coordonné), not an error.
2.2 DST DST stands for Daylight Saving Time, which adjusts local time by (usually) one hour during certain periods of the year. The rules for DST are complex (determined by local laws) and vary annually. The C library contains a table of DST rules for different regions (often read from system files for flexibility), which serves as the authoritative source for DST rules.
2.3 Epoch The epoch is the starting point of time, represented by time.gmtime(0). On all platforms, this is 1970-01-01, 00:00:00 (UTC).
2.4 Epoch Seconds These refer to the total seconds elapsed since the epoch, typically excluding leap seconds. On all POSIX-compliant platforms, leap seconds are not counted in the total seconds.
Conventions Here are some conventions to note:
3.1 Limited Past and Future This module can only handle a limited time range and may not process dates and times before the epoch or in the distant future. The boundary for the "distant future" is determined by the C library; for 32-bit systems, it's typically around 2038.
3.2 Two-Digit Years: 68 and 69 Rule The strptime() function, when encountering the %y format code, can parse years represented by two digits. When parsing two-digit years, the function follows POSIX and ISO C standards: values 69-99 are mapped to 1969-1999; values 0-68 are mapped to 2000-2068.
3.3 Old Unix Clocks Due to platform limitations, the precision of various real-time functions may be lower than the precision required or specified by their values or parameters. For example, on most Unix systems, the clock frequency is only 50 or 100 times per second.
On the other hand, time() and sleep() have better precision than their Unix equivalents: time is represented as a float, time() returns the most accurate available time, and sleep() accepts time with non-zero fractional parts.
3.4 Time Conversion Relationships Time values returned by gmtime(), localtime(), and strptime(), and accepted by asctime(), mktime(), and strftime(), are a sequence of 9 integers. The return values of gmtime(), localtime(), and strptime() also provide attribute names for individual fields. See the struct_time section for specific field attributes.
Use the following functions to convert between time representations:
| From | To | Use |
|---|---|---|
| Seconds since epoch | UTC struct_time | gmtime() |
| Seconds since epoch | Local time struct_time | localtime() |
| UTC struct_time | Seconds since epoch | calendar.timegm() |
| Local time struct_time | Seconds since epoch | mktime() |
Functions
4.8 time.process_time() Returns the combined system and user CPU time of the current process as a float (in seconds). It does not include time spent in sleep. By definition, it only applies to the process scope. The reference point of the return value is undefined, so only the difference between two calls is meaningful.
# Record start time
start_time = time.process_time()
# Perform some calculations or operations
for i in range(1000000):
pass
# Record end time
end_time = time.process_time()
# Calculate elapsed time
elapsed_time = end_time - start_time
print(f"Execution time: {elapsed_time} seconds")
4.9 time.sleep(secs) Pauses the calling thread's execution for the given number of seconds. The parameter can be a float for more precise sleep duration. If the sleep is interrupted by a signal and the signal handler doesn't raise an expection, the sleep will resume based on the recalculated delay. The pause may be longer than requested due to other activities in the system. On Windows, if secs is zero, the thread yields its remaining time slice to any other ready thread. If no other thread is ready to run, the function returns immediately and the thread continues execution. If secs is zero, Sleep(0) is used.
time.sleep(5)
print("5 seconds have passed")
4.10 time.strftime(format[, t]) Converts a time represented by a tuple or struct_time (as returned by gmtime() or localtime()) to a string according to the format parameter. If t is not provided, the current time returned by localtime() is used. format must be a string. If any field in t is out of range, a ValueError is raised.
Zero is a valid parameter at any position in the time tuple; if it's normally illegal, the value is coerced to the correct value.
The following directives can be embedded in the format string:
| Directive | Meaning | Note |
|---|---|---|
%a |
Localized abbreviated weekday name. | |
%A |
Localized full weekday name. | |
%b |
Localized abbreviated month name. | |
%B |
Localized full month name. | |
%c |
Localized appropriate date and time representation. | |
%d |
Day of the month as a decimal number [01,31]. | |
%H |
Hour (24-hour clock) as a decimal number [00,23]. | |
%I |
Hour (12-hour clock) as a decimal number [01,12]. | |
%j |
Day of the year as a decimal number [001,366]. | |
%m |
Month as a decimal number [01,12]. | |
%M |
Minute as a decimal number [00,59]. | |
%p |
Localized AM or PM. | (1) |
%S |
Second as a decimal number [00,61]. | (2) |
%U |
Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) |
%w |
Weekday as a decimal number [0(Sunday),6]. | |
%W |
Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) |
%x |
Localized appropriate date representation. | |
%X |
Localized appropriate time representation. | |
%y |
Year without century as a decimal number [00,99]. | |
%Y |
Year with century as a decimal number. | |
%z |
Time zone offset in the form +HHMM or -HHMM, where H represents decimal hours and M represents decimal minutes [-23:59, +23:59]. | |
%Z |
Time zone name (empty string if no time zone exists). Deprecated. | |
%% |
A literal '%' character. |
Notes:
- When used with the
strptimefunction, the%pdirective only affects the output hour field if the%Idirective is used to parse the hour. - The range is actually 0 to 61; value 60 is valid for timestamps representing leap seconds, and value 61 is supported for historical reasons.
- When used with the
strptimefunction,%Uand%Ware only used to specify the calculation of the weekday and year.
# Get current time
current_time = time.time()
# Format time using strftime - version 1
formatted_time = time.strftime("%H:%M:%S", time.localtime(current_time))
print("Current time (format 1):", formatted_time)
# Format time using strftime - version 2
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_time))
print("Current time (format 2):", formatted_time)
# Format short date
formatted_date = time.strftime("%d/%m/%Y", time.localtime(current_time))
print("Current time (short date):", formatted_date)
# Format long date
formatted_date = time.strftime("%A, %d %B %Y", time.localtime(current_time))
print("Current time (long date):", formatted_date)
# Format complete date and time
formatted_datetime = time.strftime("%A, %d %B %Y, %H:%M:%S", time.localtime(current_time))
print("Current time (complete):", formatted_datetime)
4.11 time.strptime(string[, format]) Parses a string representing time according to a format. Returns a struct_time as returned by gmtime() or localtime().
The format parameter uses the same directives as strftime(). It defaults to matching the format returned by ctime(): "%a %b %d %H:%M:%S %Y". If string cannot be parsed according to format, or if there's extra data after parsing, a ValueError is raised. When a more accurate value cannot be inferred, the default values used to fill any missing data are (1900, 1, 1, 0, 0, 0, 0, 1, -1). Both string and format must be strings.
# Format string for date and time
date_format = "%Y-%m-%d %H:%M:%S"
# String to parse
date_string = "2023-09-25 14:30:45"
# Parse date and time string using strptime
parsed_time = time.strptime(date_string, date_format)
# Output parsed time tuple
print("Parsed time tuple:", parsed_time)
4.12 class time.struct_time The type of the sequence of time values returned by gmtime(), localtime(), and strptime(). It's an object with a named tuple interface: values can be accessed by index and attribute name. The following values exist:
| Index | Attribute | Value |
|---|---|---|
| 0 | tm_year | (e.g., 1993) |
| 1 | tm_mon | range [1, 12] |
| 2 | tm_day | range [1, 31] |
| 3 | tm_hour | range [0, 23] |
| 4 | tm_min | range [0, 59] |
| 5 | tm_sec | range [0, 61]; see note (2) in strftime() |
| 6 | tm_wday | range [0, 6]; Monday is 0 |
| 7 | tm_yday | range [1, 366] |
| 8 | tm_isdst | 0, 1, or -1; as shown below |
| N/A | tm_zone | Abbreviation of time zone name |
| N/A | tm_gmtoff | UTC offset east of UTC in seconds |
Note that unlike the C structure, month values are in the range [1,12] rather than [0,11].
When calling mktime(), tm_isdst can be set to 1 when DST is in effect and 0 when DST is not in effect. A value of -1 indicates that it's unknown and will usually result in the correct state being filled in.
A TypeError is raised when an incorrectly sized tuple is passed to a function expecting struct_time, or when elements have the wrong type.
# Get current time
current_time = time.localtime()
# Output current time's struct_time object
print("Current time struct_time object:", current_time)
# Access individual elements of struct_time object
print("Year:", current_time.tm_year)
print("Month:", current_time.tm_mon)
print("Day:", current_time.tm_mday)
print("Hour:", current_time.tm_hour)
print("Minute:", current_time.tm_min)
print("Second:", current_time.tm_sec)
print("Weekday (0 = Monday):", current_time.tm_wday)
print("Day of year:", current_time.tm_yday)
print("DST:", current_time.tm_isdst)
4.13 time.time() Returns the time as a floating point number representing the seconds since the epoch. Handling of leap seconds depends on the specific platform. On Windows and most Unix systems, leap seconds are not counted in the seconds since epoch representation. This is commonly known as Unix time.
Note that even though time is always returned as a float, not all systems provide precision better than 1 second. Although this function usually returns non-decreasing values, it can return a lower value than a previous call if the system clock is adjusted between calls.
# Get current timestamp (seconds since 1970-01-01)
current_timestamp = time.time()
# Output current timestamp
print("Current timestamp:", current_timestamp)
# Convert timestamp to date and time string
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_timestamp))
# Output formatted date and time string
print("Formatted date and time:", formatted_time)
Timezone Constants
5.1 time.altzone Offset of the local DST timezone from UTC in seconds, if defined. If the local DST timezone is east of UTC (as in most of Western Europe, including the UK), it's negative. It's only used when daylight is non-zero.
# Get current timestamp
current_timestamp = time.time()
print("Current timestamp:", current_timestamp)
# Get current timezone offset in seconds
timezone_offset = time.altzone
print("Current timezone offset (seconds):", timezone_offset)
# Get current timezone offset in hours
timezone_offset_hours = timezone_offset / 3600
print("Current timezone offset (hours):", timezone_offset_hours)
5.2 time.daylight Non-zero if DST is enabled.
# Check if DST is currently enabled
is_dst_enabled = time.daylight
print("Is DST enabled:", is_dst_enabled)
5.3 time.timezone Offset of the local (non-DST) timezone from UTC west of UTC in seconds (negative for most of Western Europe, positive for the US, zero for the UK).
# Get current timezone offset in minutes
timezone_offset_minutes = time.timezone
print("Current timezone offset (minutes):", timezone_offset_minutes)
# Get current timezone offset in hours
timezone_offset_hours = timezone_offset_minutes / 60
print("Current timezone offset (hours):", timezone_offset_hours)
5.4 time.tzname A tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone. If the DST timezone is not defined, the second string should not be used.
# Get current timezone names
tzname = time.tzname
print("Current timezone names:", tzname)
tzname1, tzname2 = tzname[0].encode('latin-1').decode('gbk'), tzname[1].encode('latin-1').decode('gbk')
print('Current timezone names: ({}, {})'.format(tzname1, tzname2))
Related Modules
6.1 Module datetime Provides more object-oriented date and time interfaces, along with various classes for handling dates and times.
6.2 Module locale Internationalization services module. Locale settings affect the parsing of many format specifiers in strftime() and strptime.
Module calendar General calendar-related functionality module. This module's timegm() is the inverse function of gmtime().