时间格式的转化关系

time模块主要方法及使用
主要方法
time.sleep(数字):程序休眠几秒钟
time.time():获取当前时间的时间戳(以秒为单位)
time.time_ns():获取当前时间的时间戳(以纳秒为单位)
time.localtime():获取当前的本地时间,结果是一个 struct_time 类的对象
time.localtime(时间戳-秒):返回时间戳对应的本地时间,结果是一个 struct_time 类的对象
time.mktime(struct_time对象):返回时间对应的时间戳(秒为单位)
time.strftime(格式化字符串, 日期):将日期数据(struct_time对象)格式化一个字符串
time.strptime(日期字符串,格式化字符串):将日期字符串转换为一个日期数据(struct_time对象)
格式化字符串符号
%Y:4位数字的年份
%m:2位数字的月份
%d:2位数字的日期
%H:24小时制的小时
%M:2位数字的分钟
%S:2位数字的秒
使用示例
import time
"""
time.sleep(数字):程序休眠几秒钟
time.time():获取当前时间的时间戳(以秒为单位)
time.time_ns():获取当前时间的时间戳(以纳秒为单位)
time.localtime():获取当前的本地时间,结果是一个 struct_time 类的对象
time.localtime(时间戳-秒):返回时间戳对应的本地时间,结果是一个 struct_time 类的对象
time.mktime(struct_time对象):返回时间对应的时间戳(秒为单位)
time.strftime(格式化字符串, 日期):将日期数据(struct_time对象)格式化一个字符串
time.strptime(日期字符串,格式化字符串):将日期字符串转换为一个日期数据(struct_time对象)
"""
# time.sleep()
time.sleep(1) # 程序休眠1秒
# time.time() 获取当前时间的时间戳(以秒为单位)
print(time.time()) # 1698204425.088401
# time.time_ns() 获取当前时间的时间戳(以纳秒为单位)
print(time.time_ns()) # 1698204425088401100
# time.localtime() 获取当前的本地时间,结果是一个 struct_time 类的对象
print(time.localtime())
"""time.struct_time(tm_year=2023, tm_mon=10, tm_mday=25, tm_hour=11, tm_min=27, tm_sec=5, tm_wday=2, tm_yday=298, tm_isdst=0)"""
# time.localtime(时间戳-秒) 返回时间戳对应的本地时间,结果是一个 struct_time 类的对象
print(time.localtime(time.time()))
"""time.struct_time(tm_year=2023, tm_mon=10, tm_mday=25, tm_hour=11, tm_min=27, tm_sec=5, tm_wday=2, tm_yday=298, tm_isdst=0)"""
# time.mktime(struct_time对象) 返回时间对应的时间戳(秒为单位)
print(time.mktime(time.localtime())) # 1698204425.0
# time.strftime(格式化字符串, 日期) 将日期数据(struct_time对象)格式化一个字符串
print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())) # 2023/10/25 11:27:05
# time.strptime(日期字符串,格式化字符串) 将日期字符串转换为一个日期数据(struct_time对象)
print(time.strptime("2023/10/25 11:09:59", "%Y/%m/%d %H:%M:%S"))
"""time.struct_time(tm_year=2023, tm_mon=10, tm_mday=25, tm_hour=11, tm_min=27, tm_sec=5, tm_wday=2, tm_yday=298, tm_isdst=0)"""
1万+

被折叠的 条评论
为什么被折叠?



