Python中处理时间数据的常用函数主要位于`time`和`datetime`模块中。下面是一些基本的时间函数及其用法:
time模块
1. `time.time()`
获取当前时间戳(自1970年1月1日午夜以来的秒数)。
import time
current_timestamp = time.time()
print("当前时间戳:", current_timestamp)
2. `time.localtime()`
将时间戳转换为本地时间结构体(`struct_time`)。
import time
local_time = time.localtime(time.time())
print(local_time)
3. `time.ctime(seconds)`
将时间戳转换为可读格式的字符串。
import time
readable_time = time.ctime(time.time())
print("可读时间:", readable_time)
4. `time.sleep(seconds)`
使当前线程暂停指定的秒数。
import time
time.sleep(5) 暂停5秒
5. `time.asctime([struct_time])`
将`struct_time`对象转换为可读格式的字符串。
import time
current_time = time.localtime()
print(time.asctime(current_time))
6. `time.clock()`
返回程序运行时的时间(浮点数表示)。
import time
start_time = time.clock()
time.sleep(1)
end_time = time.clock()
print("程序运行时间:", end_time - start_time)
datetime模块
1. `datetime.datetime.now()`
获取当前的日期和时间。
from datetime import datetime
current_datetime = datetime.now()
print("当前日期和时间:", current_datetime)
2. `strftime(format_string)`
将日期时间对象格式化为字符串。
from datetime import datetime
current_datetime = datetime.now()
formatted_time = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("格式化时间:", formatted_time)
3. `strptime(string, format_string)`
将字符串解析为日期时间对象。
from datetime import datetime
date_string = "2024-05-15 14:30:00"
parsed_datetime = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("解析时间:", parsed_datetime)
4. `timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)`
表示两个日期或时间之间的差异。
from datetime import timedelta
one_day = timedelta(days=1)
print("一天的时间间隔:", one_day)
以上是Python中一些基本的时间函数及其用法。您可以根据需要选择合适的函数来处理日期和时间数据
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/138724.html