我得到了这个,但是如何在其中插入日期,我想要的日期是从当前时间开始的一个月
print('''
{} will play football on Y
'''.format(name1))
其中Y是距离当前时间一个月
答案 0 :(得分:2)
提示:要获取当年的当前月份,请使用datetime
模块:
>>> import datetime
>>> datetime.datetime.now().month
8
datetime.datetime.now()
将当前时间作为datetime
对象获取,.month
属性打印当前月份(作为数字)
答案 1 :(得分:1)
from datetime import *
monthNames=["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
name1 = str(input("Please input your name: "))
thisMonth = int(datetime.now().month)
thisMonth_name = monthNames[thisMonth]
print("%s will play football on %s" %(name1, thisMonth_name))
OR
import datetime as dt
import calendar
name1 = str(input("Please input your name: "))
thisMonth = int(dt.datetime.now().month)+1
monthName = str(calendar.month_name[thisMonth])
print("%s will play football on %s" %(name1, monthName))
另见:Get month name from number
https://docs.python.org/3/library/datetime.html
https://docs.python.org/3/library/calendar.html#calendar.month_name
答案 2 :(得分:0)
通过这种方式操作日期和时间的最简单方法通常是使用arrow库。在这种情况下,您可以使用此代码获得所需内容:
>>> import arrow
>>> arrow.now().shift(months=+1).format('MMMM')
'September'
答案 3 :(得分:0)
如果您想从当前时间开始一个月后打印日期时间,
您可以组合使用datetime
和dateutil
。
from datetime import date, datetime
from dateutil import relativedelta
today = datetime.today()
monthplus1 = today + relativedelta.relativedelta(months=1)
print today
print monthplus1
# output
> datetime.datetime(2017, 8, 31, 8, 52, 3, 75585)
> datetime.datetime(2017, 9, 30, 8, 52, 3, 75585)
然后您可以使用monthplus1.month
等日期时间属性来获取下个月。
如果您想要月份名称,请使用如下面的答案
monthNames=["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
稍微调整,所以第0个将为空,你可以获得月份名称
monthNames[monthplus1.month]
> 'September'
然后像使用格式
那样正常地使用这些值print('''
{} will play football on {}
'''.format(name1, monthNames[monthplus1.month]))