Python 3 – time asctime() Method
The asctime()
method is a part of the time
module in Python 3. It is used to convert a tuple representing a time to a string in the following format: Day Month Date Hour:Minute:Second Year
.
Here’s a simple example:
import time
t = (2022, 2, 10, 16, 55, 47, 0, 0, 0)
s = time.asctime(t)
print(s)
In this example, we first import the time
module. Then, we create a tuple t
representing a time. We use asctime()
to convert this tuple to a string and store it in the variable s
. Finally, we print s
.
The output of this code will be:
'Thu Feb 10 16:55:47 2022'
Syntax
The syntax of the asctime()
method is:
time.asctime([t])
Here, t
is an optional argument. It represents a tuple representing a time. If t
is not specified, then the current local time is used.
Example
import time
# current time
print("Current time:", time.asctime())
# custom time
t = (2022, 2, 10, 16, 55, 47, 0, 0, 0)
print("Custom time:", time.asctime(t))
Output:
Current time: Sat Feb 12 12:58:02 2022
Custom time: Thu Feb 10 16:55:47 2022
Explanation
In the first part of the example, we use asctime()
with no arguments to convert the current local time to a string.
In the second part, we create a tuple t
representing a custom time and use asctime()
to convert it to a string.
Conclusion
The asctime()
method is a useful tool for converting a tuple representing a time to a string in a readable format. Keep in mind that the string format produced by asctime()
may vary depending on the locale.