python基础——时间(time&datatime)

1.time

复制代码
import time

# 获取当前时间,时间戳 从1970年1月1日0点0分0秒 到此刻的秒数
now = time.time()
print(f"{now=}",type(now))   #浮点数

# 获取当前时间,标准时间 年月日,时分秒
now_st = time.localtime(now)
print(f"{now_st}",type(now_st))  #时间对象实例time.struct_time

# 时间转字符,格式化
now_str = time.strftime("%Y-%m-%d %H:%M:%S", now_st)
print(f"{now_str}",type(now_str))

time.sleep(2) # 暂停2秒 # 字符串转时间

#字符转时间
past_st = time.strptime("2022-08-05 21:57:54", "%Y-%m-%d %H:%M:%S")
print(f"{past_st}",type(past_st))  #时间对象实例time.struct_time

# 时间转时间戳
past = time.mktime(past_st)
print(f"{past}",type(past))

>>>

now=1659978197.715609 <class 'float'>
time.struct_time(tm_year=2022, tm_mon=8, tm_mday=9, tm_hour=1, tm_min=3, tm_sec=17, tm_wday=1, tm_yday=221, tm_isdst=0) <class 'time.struct_time'>
2022-08-09 01:03:17 <class 'str'>
time.struct_time(tm_year=2022, tm_mon=8, tm_mday=5, tm_hour=21, tm_min=57, tm_sec=54, tm_wday=4, tm_yday=217, tm_isdst=-1) <class 'time.struct_time'>
1659707874.0 <class 'float'>

复制代码

2. datetime

复制代码
import time
import datetime

now = datetime.datetime.now() # 当前时间,时间d实例对象atetime.datetime
print(f"{now=}",type(now))

print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)

#时间转时间戳
print(now.timestamp(),type(now.timestamp())) # 转为时间戳
time.sleep(1) # 暂停

#时间戳转时间
past = datetime.datetime.fromtimestamp(now.timestamp()) #时间实例对象datetime.datetime
print(f"{past}",type(past))

>>>

now=datetime.datetime(2022, 8, 9, 1, 2, 3, 974984) <class 'datetime.datetime'>
2022
8
9
1
2
3
1659978123.974984 <class 'float'>
2022-08-09 01:02:03.974984 <class 'datetime.datetime'>

复制代码

 3.计算时间差

复制代码
import datetime
import time

t1 = time.time() # 时间戳 数字
dt1 = datetime.datetime.now() # dt 实例对象
time.sleep(2)
t2 = time.time() # 时间戳 数字
dt2 = datetime.datetime.now() # dt 实例对象
print(f"{t2- t1=}") # 差值是数字
print(f"{dt2- dt1=}") # 差值是对象

>>>

t2- t1=2.0110411643981934
dt2- dt1=datetime.timedelta(seconds=2, microseconds=11041

复制代码

 

posted @   奋斗的sunny  阅读(312)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示