python时间戳、时间和日期的加减、日期和时间的隔差
获取当前时间:
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(localtime) #打印: 2022-01-04 19:44:47 进程已结束,退出代码为 0
获取当前时间戳:如果想让小数点后移,则*10即可
import time
localtime = time.time() print(localtime)
# 打印
1641297004.802891
# 想去掉小数点加int
时间与时间戳之间的转换:
import time # 时间转换成时间戳 tss1 = '2022-03-29 00:00:00' timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S") timeStamp = int(time.mktime(timeArray)) print(timeStamp) # 10位时间戳转换成时间 timeStamp = 1648483200 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)
# 13位时间戳转成时间 tre_timeArray = time.localtime(1646012206685/1000) tre_otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", tre_timeArray) print('tre_otherStyleTime',tre_otherStyleTime)
>>>1648483200 >>>2022-03-29 00:00:00
时间和日期的加减:
from datetime import datetime from dateutil.relativedelta import relativedelta # 加1年 print((datetime.now() + relativedelta(years=1)).strftime("%Y-%m-%d")) # 加1个月 print((datetime.now() + relativedelta(months=1)).strftime("%Y-%m-%d")) # 加1天 print((datetime.now() + relativedelta(days=1)).strftime("%Y-%m-%d")) # 加1小时 print((datetime.now() + relativedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")) # 加1分钟 print((datetime.now() + relativedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S")) 打印结果 2023-06-29 2022-07-29 2022-06-30 2022-06-29 17:07:58 2022-06-29 16:08:58
日期的隔差:
import datetime from dateutil import rrule d1 = datetime.date(2021, 9, 26) d2 = datetime.date(2022, 2, 11) months = rrule.rrule(rrule.MONTHLY, dtstart=d1, until=d2).count() print("两者日期隔差为:", f"months={months}") 打印结果 两者日期隔差为: months=5
打印各种格式日期:
import time # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))) 打印结果 2022-06-29 16:18:10 Wed Jun 29 16:18:10 2022 1459175064.0