python格式化时间,取值字符串年月

啥也不说了,直接上代码。
首先需要导入python自带的datetime模块。
import datetime
# 导入日期扩展库
from dateutil.relativedelta import relativedelta
# 当前 年 月 日
today = datetime.date.today()
# 下下个月
last_2_month = today + relativedelta(months=+2)  # 下两个月,下N个月参数为(months=-N)
next_two_months = datetime.datetime.strftime(last_2_month, "%Y-%m")
# 下月
last_2_month = today + relativedelta(months=+1)  # 下个月,下个月参数为(months=-1)
next_month = datetime.datetime.strftime(last_2_month, "%Y-%m")

# 本月(年月)
str_now = datetime.datetime.strftime(today, "%Y-%m")

# 上月
last_month = today + datetime.timedelta(days=-today.day)
str_last = datetime.datetime.strftime(last_month, "%Y-%m")

# 上2个月
last_2_month = today + relativedelta(months=-2)  # 上两个月,上N个月参数为(months=-N)
two_months = datetime.datetime.strftime(last_2_month, "%Y-%m")  

###所有输出结果都是字符串类型(例2019-08),可以根据自己的需求格式化时间输出。


作者:weixin_43108474
来源:CSDN
版权声明:本文为博主原创文章,转载请附上博文链接!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值