python时间和日期处理

1.时间处理

time相关操作:

  • 获取当前时间
  • 时间转字符串
  • 字符串转时间
  • 计算时间差
import time

now=time.time() #时间戳 从1970年1月1日0点0分0秒到此刻的秒数

print(f"{now=}")

now_st=time.localtime(now) #标准时间 年月日,时分秒
print(f"{now_st}")

now_str=time.strftime("%Y-%m-%d %H:%M:%S",now_st) #格式化之后的字符串
print(f"{now_str}")

#字符串转时间
last_time=time.strptime("2023-06-05 11:20:29","%Y-%m-%d %H:%M:%S")
print(f"{last_time=}")

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

2.日期处理

import datetime
import time

now=datetime.datetime.now()#当前时间
print(f"{now=}")
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)

print(now.timestamp()) #转为时间戳

time.sleep(2)
past=datetime.datetime.fromtimestamp(now.timestamp()) #时间戳转dt
print(f"{past}")

#时间差
t1=time.time() #时间戳 数字
dt1=datetime.datetime.now() #datetime 实例对象

time.sleep(3)

t2=time.time()
dt2=datetime.datetime.now()

print(f"{t2-t1=}") #差值是数字
print(f"{dt2-dt1=}") #差值是datetime对象

计算机底层:浮点数

python中的时间

  • 计算机底层:二进制
  • 时间戳:浮点数
  • 标准时间:年月日
  • datetime:面向对象的年月日

 

相关练习:

#1.编写函数f1,动态获取今天的日期,保存到today.txt文件中
def f1():
    #now_st=time.localtime(time.time())
    now_st=datetime.datetime.now()
    now_str=now_st.strftime("%Y-%m-%d")
    f=open("today.txt","wt",encoding="utf-8")
    f.write(now_str)
    f.close()

#2.编写函数f2,today.txt文件中获取日期,计算该日期距离国庆节,还差几天
def f2():
    f=open("today.txt","rt",encoding="utf-8")
    now=f.read()
    f.close()
    year=datetime.datetime.now().year
    gq=str(year)+"-10-01"
    last_time = datetime.datetime.strptime(gq, "%Y-%m-%d")
    now_time=datetime.datetime.strptime(now,"%Y-%m-%d")
    days=last_time-now_time
    print(f"距离国庆还有:{days}天")

f1()
f2()

  

posted @ 2023-06-05 18:43  万溪汇海  阅读(20)  评论(0编辑  收藏  举报