社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中递增月份,然后打印递增月份的名称

Kaushal • 6 年前 • 1767 次点击  

有没有办法打印递增月份的名称?

import datetime
currentDT = datetime.datetime.now()
currentmonth=currentDT.strftime("%B")
nextmonth = datetime.date.today().month + 1

这里我得到整数形式的“下一个月”。

7

但是我怎样才能知道那个月的名字,也就是七月。我甚至试过用这个,

next_month=nextmonth.strftime("%B")

但它返回了错误,

AttributeError: 'int' object has no attribute 'strftime'
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/34310
 
1767 次点击  
文章 [ 4 ]  |  最新文章 6 年前
SmartManoj
Reply   •   1 楼
SmartManoj    6 年前

对于像十二月这样的边缘案例 calendar.month_name 有13个元素

import calendar
import datetime
months=calendar.month_name[1:]
a=months[datetime.date.today().month % 12]
print(a)
Rajan Sharma
Reply   •   2 楼
Rajan Sharma    6 年前

你可以这样做 python 3

import time,datetime

currentDT = datetime.datetime.now()
currentmonth=currentDT.strftime("%B")
nextmonth = datetime.date.today().month + 1
print(time.strftime('%B', time.struct_time((0, nextmonth, 0,)+(0,)*6)))
Azat Ibrakov Sakib Farhad
Reply   •   3 楼
Azat Ibrakov Sakib Farhad    6 年前

你可以用 calendar module

import calendar
print (calendar.month_name[4])

它是内置的。

Azat Ibrakov
Reply   •   4 楼
Azat Ibrakov    6 年前

你的问题是 nextmonth 是一个 int 代表月份,不是 date 对象,以便使用 calendar.month_name array 喜欢

>>> import calendar
>>> calendar.month_name[(datetime.date.today().month + 1) % 12]
'July'