插件窝 干货文章 python时间日期相加减的实现示例

python时间日期相加减的实现示例

datetime relativedelta class dateutil 268    来源:    2024-10-17

前言

时间日期相加减,单独看没啥意思,但是比如要预测从当前时间开始,未来12个月的股票变化情况,你只拿到了股票的价格的序列值一共12个,需要把它扑到未来12个月,中间可能跨年。

安装插件

python-dateutil

pip install python-dateutil

一、python时间处理月份加减

import datetime
from dateutil.relativedelta import relativedelta
 
datetime_now = datetime.datetime.now()
datetime_three_month_ago = datetime_now - relativedelta(months=3)
print(datetime_three_month_ago)

二、python日期相减(秒、小时、天、月、年)

1.例子

代码如下(示例):

import datetime
today=datetime.datetime.now()
datetime1=today-datetime.timedelta(seconds=10)#减10秒
datetime2=today-datetime.timedelta(minutes=10)#减10分钟
datetime3=today-datetime.timedelta(hours=1)#减1小时
datetime4=today-datetime.timedelta(days=7)#减1天
datetime5=today-datetime.timedelta(weeks=1)#减1周
datetime6=today.strftime('%Y-%m-%d')#将时间格式化为字符串
print('today:',today)
print('second:',datetime1)
print('minute:',datetime2)
print('hour:',datetime3)
print('day:',datetime4)
print('week:',datetime5)
print('时间格式化为字符串:',datetime6)
  
  
import dateutil.relativedelta
datetime7= datetime.datetime.strptime(datetime6, '%Y-%m-%d')#将字符串格式为时间
datetime8 = datetime7 - dateutil.relativedelta.relativedelta(seconds=10)#减10秒
datetime9 = datetime7 - dateutil.relativedelta.relativedelta(minutes=10)#减10分钟
datetime10 = datetime7 - dateutil.relativedelta.relativedelta(hours=1)#减减1小时
datetime11 = datetime7 - dateutil.relativedelta.relativedelta(days=1)#减1天
datetime12 = datetime7 - dateutil.relativedelta.relativedelta(months=1)#减一个月
datetime13 = datetime7 - dateutil.relativedelta.relativedelta(years=1)#减一年
print('字符串格式为时间:',datetime7)
print('second2:',datetime8)
print('minute2:',datetime9)
print('hour2:',datetime10)
print('day2:',datetime11)
print('month2:',datetime12)
print('year:',datetime13)

2.案例:

处理未来12个月

def get_dynamic_year(i):
    today=datetime.datetime.now()
    tmp = today + dateutil.relativedelta.relativedelta(months=i)
    return tmp.year

def get_dynamic_month(i):
    today=datetime.datetime.now()
    tmp = today + dateutil.relativedelta.relativedelta(months=i)
    return tmp.month

pd_insert["year"] = [get_dynamic_year(i) for i in range(null,13)]
pd_insert["month"] = [ get_dynamic_month(i) for i in range(null,13) ]

处理未来7天的日期

    """
    pandas实在是太变态了,用row.name的方式获取行索引
    把每一天都加上
    """
    data_date = today + datetime.timedelta(days=i+1)
    return data_date.strftime("%Y-%m-%d")
pd_insert['forecast_date'] = today.strftime("%Y-%m-%d")
pd_insert['data_date'] = pd_insert.apply(
         lambda x: get_date(x.name, x['forecast_date']), axis=1)

总结

到此这篇关于python时间日期相加减的实现示例的文章就介绍到这了,更多相关python时间日期相加减内容请搜索插件窝以前的文章或继续浏览下面的相关文章希望大家以后多多支持插件窝!