在我们讨论 Python time.asctime() 方法的工作原理之前,让我们了解一下时间的不同表示方式。
在 Python time 模块中,时间可以用两种简单的方式表示:元组或对象。元组更抽象;它按元组的每个元素表示特定时间元素的顺序存储日期和时间。例如,(2023, 1, 9, 10, 51, 77, 0, 9, 0) 表示时间 “Mon Jan 9 10:51:77 2023”。但在这里,仅通过查看元组无法破译哪个元素表示什么。这就是为什么引入一个对象以更清楚地理解这些元素的原因。
对象(通常表示为 struct_time)定义各种字段来保存各种时间元素。因此,访问它们变得更加容易。例如,对象将时间表示为 (tm_year=2023, tm_mon=1, tm_mday=9, tm_hour=10, tm_min=51, tm_sec=77, tm_wday=0, tm_yday=9, tm_isdst=0)。
asctime() 方法将此元组或struct_time转换为以下格式的 24 个字符的字符串(以 UTC 或本地时间表示):'Mon Jan 9 10:51:77 2023'。在此字符串中,day 字段分配了两个字符,因此如果它是个位数的 day,则在其前面填充空格。
但是,与 asctime() C 函数不同,此方法不会向字符串添加尾随换行符。
语法
以下是 Python time asctime() 方法的语法 -
time.asctime([t]))
参数
- t (可选)−这是一个由 9 个元素或 struct_time 组成的元组,表示 UTC 时间或本地时间。
返回值
此方法返回以下格式的 24 个字符的字符串:'Tue Feb 17 23:21:05 2009'。
例以下示例显示了 Python time asctime() 方法的用法。在这里,我们尝试使用 asctime() 方法以 24 个字符的字符串格式表示由 localtime() 方法返回的印度当前本地时间。
import time
t = time.localtime()
lc = time.asctime(t)
print("Current local time represented in string:", lc)
当我们运行上述程序时,它会产生以下结果——
例
此方法还会将 UTC 时间转换为字符串格式。
在此示例中,使用 gmtime() 方法检索当前 UTC 时间,并将此 UTC 时间作为参数传递给 asctime() 方法。当前时间从 struct_time 对象转换为 24 个字符的字符串。
import time
t = time.gmtime()
gm = time.asctime(t)
print("Current UTC time represented in string:", gm)
让我们编译并运行上面的程序,以产生以下结果——
例
如果未向此方法传递任何参数,则结果字符串默认表示本地时间。
import time
ct = time.asctime()
print("Current time represented in string is", ct)
输出
例
从 localtime() 和 gmtime() 方法获取的返回值采用 struct_time 对象的形式;要将此方法的参数作为 Tuples 传递,必须手动创建它,如下例所示。
import time
# Create a tuple representing the current local time
t = (2024, 1, 9, 11, 40, 57, 0, 9, 0)
# Pass this tuple as an argument to the method
ct = time.asctime(t)
# Display the string output
print("Current local time represented in string", ct)
输出