在项目中,我们常常要对时间进行处理,所以会用到常用的time、datetime等模块。今天,分享下关于时间处理的一些方法
import datetime
import time
# 获取当前时间的时间戳
old_time = time.time()
# 休眠 2 秒
time.sleep(2)
new_time = time.time()
# 计算刚才程序运行了多长时间
deffer = new_time - old_time
print(deffer)
# 结果 2.0004806518554688
# 获取时间的本地时间
print(time.localtime())
# 结果 time.struct_time(tm_year=2019, tm_mon=6, tm_mday=5, tm_hour=23, tm_min=7, tm_sec=49, tm_wday=2, tm_yday=156, tm_isdst=0)
# 获取现在的时间
print(datetime.datetime.now())
# 结果 2019-06-05 22:20:50.529918
# 获取Utc 时间
print(datetime.datetime.utcnow())
# 结果 2019-06-05 14:21:25.277175
# 获取今天的日期
print(datetime.date.today())
# 结果 2019-06-05
# 获取现在的年,月,日, 时分秒
print(datetime.datetime.now().year)
print(datetime.datetime.now().month)
print(datetime.datetime.now().day)
print(datetime.datetime.now().hour)
print(datetime.datetime.now().minute)
print(datetime.datetime.now().second)
# 格式化输出年月日,时分秒
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 结果 2019-06-05 22:32:01
# 将字符串转化为时间格式
time_1 = datetime.datetime.strptime('2019-06-03 20:04:12', "%Y-%m-%d %H:%M:%S")
print(time_1, type(time_1))
# 结果 2019-06-03 20:04:12 <class 'datetime.datetime'>
# 计算时间差 可以到 星期,日,时,分秒,使用 timedelta 模块
from datetime import timedelta
now = datetime.datetime.now()
differ = now - time_1
print(differ)
# 结果 2 days, 2:35:47.053063
# 差多少 天,秒
print(differ.days)
print(differ.seconds)
# 结果 2 9515
# 现在之后的两个小时, 一星期前的时间
print(now) # 2019-06-05 22:44:25.498303
print(now+timedelta(hours=2)) # 2019-06-06 00:44:25.498303
print(now - timedelta(weeks=1)) # 2019-05-29 22:50:42.675893
# 月份\年份的加减 使用 python-dateutil 中的模块
# 安装 pip install python-dateutil
from dateutil.relativedelta import relativedelta
print(now + relativedelta(months=2)) # 2019-08-05 22:57:44.763038
print(now-relativedelta(months=3)) # 2019-03-05 22:57:44.763038
print(now+relativedelta(years=2)) # 2021-06-05 22:58:54.204071
print(now-relativedelta(years=3)) # 2016-06-05 22:59:25.968395