python时间函数调用
时间: 2023-07-20 14:40:05 浏览: 57
在 Python 中,可以使用 `time` 模块来进行时间函数的调用。以下是一些常用的时间函数:
1. `time.time()`:返回当前时间的时间戳(1970年1月1日以来的秒数)。
2. `time.localtime([secs])`:将一个时间戳转换为当前时区的 struct_time。如果未指定时间戳,则使用当前时间戳。
3. `time.strftime(format[, t])`:将 struct_time 转换为指定格式的字符串。
4. `time.sleep(secs)`:推迟调用线程的运行,secs 参数指秒数。
示例代码:
```python
import time
# 获取当前时间戳
timestamp = time.time()
print("当前时间戳为:", timestamp)
# 将时间戳转换为 struct_time
localtime = time.localtime(timestamp)
print("当前时间为:", localtime)
# 将 struct_time 转换为字符串
format_time = time.strftime("%Y-%m-%d %H:%M:%S", localtime)
print("当前时间字符串为:", format_time)
# 推迟程序运行
time.sleep(2)
print("程序运行结束")
```
输出结果:
```
当前时间戳为: 1634114789.307118
当前时间为: time.struct_time(tm_year=2021, tm_mon=10, tm_mday=13, tm_hour=16, tm_min=46, tm_sec=29, tm_wday=2, tm_yday=286, tm_isdst=0)
当前时间字符串为: 2021-10-13 16:46:29
程序运行结束
```