Python time time() 方法返回当前 UTC 时间。此返回值以浮点数的形式获取,以自纪元以来的秒数表示。
此方法不接受任何参数,因此,它始终返回当前 UTC 时间。
注 − 尽管时间始终以浮点数的形式返回,但并非所有系统都提供比 1 秒精度更高的时间。
虽然此函数通常返回非递减值,但如果系统时钟在两次调用之间被设置回去,则它可以返回比前一次调用更低的值。
为了避免这种精度损失,可以使用 time_ns() 方法。
虽然此函数通常返回非递减值,但如果系统时钟在两次调用之间被设置回去,则它可以返回比前一次调用更低的值。
为了避免这种精度损失,可以使用 time_ns() 方法。
语法
以下是 Python time time() 方法的语法 -
time.time()
参数
此方法不接受任何参数。
返回值
该方法返回 UTC 的当前时间。
例以下示例显示了 time() 方法的用法。
import time
t = time.time()
print("Current UTC Time in seconds:", t)
当我们运行上述程序时,它会产生以下结果——
Current UTC Time in seconds: 1673432458.9977512
例
可以通过将 time() 方法获取的返回值作为参数传递给 gmtime() 或 strftime() 等方法来格式化它。
在以下示例中,我们使用 time() 方法获取当前时间(以秒为单位)。这些秒数作为参数传递给 gmtime() 方法,以使用 struct_time 对象的各种字段来表示它,以指示时间元素。但是,作为额外的步骤,我们也可以尝试通过将它作为参数传递给 strftime() 方法来简化此对象的结构。
import time
t = time.time()
print("Current UTC Time in seconds:", t)
#Formatting the seconds obtained from time() using gmtime()
fmt = time.gmtime(t)
print("Current Formatted UTC Time:", fmt)
#Formatting the object obtained from gmtime() using strftime()
strf = time.strftime("%D %T", fmt)
print("Current Formatted UTC Time:",strf)
输出
Current UTC Time in seconds: 1673435474.7526345
Current Formatted UTC Time: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=11, tm_hour=11, tm_min=11, tm_sec=14, tm_wday=2, tm_yday=11, tm_isdst=0)
Current Formatted UTC Time: 01/11/23 11:12:11
Current Formatted UTC Time: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=11, tm_hour=11, tm_min=11, tm_sec=14, tm_wday=2, tm_yday=11, tm_isdst=0)
Current Formatted UTC Time: 01/11/23 11:12:11
例
不仅仅是 UTC 时间,我们还可以通过将此方法的返回值作为参数传递给 localtime() 方法来计算本地时间。
我们讨论了 time() 方法处理 UTC 时间,并返回自 UTC 时间纪元以来经过的秒数。但是,如果我们从时区的角度考虑,则表示 UTC 中这些秒数的浮点数将等于本地时间中的秒数。因此,我们还可以使用 localtime() 方法通过传递 time() 方法的返回值来格式化当前本地时间。
import time
t = time.time()
print("Current UTC Time in seconds:", t)
#Formatting the seconds obtained using localtime()
fmt = time.localtime(t)
print("Current Formatted Local Time:", fmt)
#Formatting the seconds obtained using strftime()
strf = time.strftime("%D %T", fmt)
print("Current Formatted Local Time:",strf)
如果我们编译并运行上面的程序,输出显示如下 -
Current UTC Time in seconds: 1673438690.5065289
Current Formatted Local Time: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=11, tm_hour=17, tm_min=34, tm_sec=50, tm_wday=2, tm_yday=11, tm_isdst=0)
Current Formatted Local Time: 01/11/23 17:34:50
Current Formatted Local Time: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=11, tm_hour=17, tm_min=34, tm_sec=50, tm_wday=2, tm_yday=11, tm_isdst=0)
Current Formatted Local Time: 01/11/23 17:34:50