|
| 1 | +--- |
| 2 | +Title: 'asctime()' |
| 3 | +Description: 'Converts a time tuple or `struct_time` to a 24‑character human‑readable string.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Functions' |
| 9 | + - 'Methods' |
| 10 | + - 'Python' |
| 11 | + - 'Time' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`time.asctime()`** Python function converts a time value (a 9‑element tuple or `time.struct_time`) into a readable, 24‑character string such as `'Wed Sep 17 19:40:37 2025'`. |
| 18 | + |
| 19 | +## Syntax of `time.asctime()` |
| 20 | + |
| 21 | +```pseudo |
| 22 | +import time |
| 23 | +
|
| 24 | +time.asctime(t) |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `t` (optional): A 9‑tuple or `time.struct_time` representing a UTC or local time, with fields `(year, month, mday, hour, min, sec, wday, yday, isdst)` as produced by `time.localtime()` or `time.gmtime()`. |
| 30 | + - If omitted, `time.asctime()` uses `time.localtime()`. |
| 31 | + - `wday` (weekday) and `yday` (day of year) are ignored. |
| 32 | + - `isdst` may be `-1`, `0`, or `1`. |
| 33 | + |
| 34 | +**Return value:** |
| 35 | + |
| 36 | +- `str`: A 24‑character string of the form `'Sun Jun 20 23:21:05 1993'`. The day of month is two characters wide and space‑padded if needed (e.g., `'Wed Sep 17 19:40:37 2025'`). |
| 37 | + |
| 38 | +## Example |
| 39 | + |
| 40 | +Convert the current local time (from `localtime()`) and show the default call with no arguments: |
| 41 | + |
| 42 | +```py |
| 43 | +import time |
| 44 | + |
| 45 | +# Using localtime() with asctime() |
| 46 | +t = time.localtime() |
| 47 | +lc = time.asctime(t) |
| 48 | +print("Current local time represented in string:", lc) |
| 49 | + |
| 50 | +# Default call (formats current local time) |
| 51 | +print(time.asctime()) |
| 52 | +``` |
| 53 | + |
| 54 | +Example output: |
| 55 | + |
| 56 | +```shell |
| 57 | +Current local time represented in string: Wed Sep 17 19:40:37 2025 |
| 58 | +Wed Sep 17 19:40:37 2025 |
| 59 | +``` |
| 60 | + |
| 61 | +> **Note:** The exact output will vary depending on when the function is run. |
| 62 | +
|
| 63 | +## Codebyte |
| 64 | + |
| 65 | +Run this to see `time.asctime()` in action with local time, a UTC `struct_time`, and a custom tuple: |
| 66 | + |
| 67 | +```codebyte/python |
| 68 | +import time |
| 69 | +
|
| 70 | +# No argument → formats the current local time |
| 71 | +print("Current local time:", time.asctime()) |
| 72 | +
|
| 73 | +# Using an explicit 9-tuple |
| 74 | +# Format: (year, month, day, hour, minute, second, weekday, yearday, isdst) |
| 75 | +custom_time = (2025, 9, 17, 10, 30, 0, 0, 0, -1) |
| 76 | +print("Custom tuple:", time.asctime(custom_time)) |
| 77 | +``` |
0 commit comments