Python 内置库 -- 科学计算与时间日期

math函数可以提供很多数学计算的帮助

数字常量:

math.pi :圆周率

math.e :自然对数

math.inf :正无穷大,-math.inf 负无穷大

nath.nan:非数字

数论和表示函数:可百度

 

Python中处理时间的模块:

time

datetime

常见的时间表示形式:

时间戳

格式化的时间字符串

datetime场用的类:

datetime

timedelta

timezone

练习1 获取当前的时间/获取特定的时间:

import datetime

now = datetime.datetime.now()
print(now)
print(now.day)
print(now.month)
print(now.year)
#转成时间戳
print(now.timestamp())

#指定时间
print(datetime.datetime(2022, 12, 2))

练习2 字符串与时间的互转

#change str to datetime
s = "2022-04-30 15:22:24"
s1 = datetime.datetime.strptime(s,'%Y-%m-%d %H:%M:%S')
print(s1)
print(type(s1))
#change datetime to str
now = datetime.datetime.now()
res = now.strftime('%a,%b %d %H:%M')
print(res)
print(type(res))

输出:

2022-04-30 15:22:24
<class 'datetime.datetime'>
Sat,Apr 30 15:33
<class 'str'>

练习3 时间戳与时间互转

stamp = 1651304300.192182
#change time stamp to date time
s = datetime.datetime.fromtimestamp(stamp)
print(s)
#change date time back to time stamp
print(s.timestamp())

输出:

2022-04-30 15:38:20.192182
1651304300.192182

 

练习:创建一个函数,生成一个以时间命名并记录log的文件

def createfile():
    now = datetime.datetime.now()
    current_time = now.strftime('%Y%m%d_%H%M%S')
    print(current_time)
    name = current_time+'.log'
    with open(name,'w+',encoding='utf-8') as f:
        message = f'{now} [info] line:14 this is log ..'
        f.write(message)

createfile()

  

 

posted @   lms21  阅读(91)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示