python时间和日期处理

1.时间处理

time相关操作:

  • 获取当前时间
  • 时间转字符串
  • 字符串转时间
  • 计算时间差
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.日期处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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 @   万溪汇海  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示