2017-08-31 51 views
-1

我得到了這一點,但如何插入日期到了,我要的日期是從當前時間的Python:我怎麼添加日期到這個

print(''' 

{} will play football on Y 

'''.format(name1)) 

從而使Y是一個月後1個月從當前時間

+2

你到目前爲止嘗試過什麼? –

+1

查看['datetime'](https://docs.python.org/3/library/datetime.html)模塊。 –

回答

2

提示:爲了得到一年的當月,使用datetime模塊:

>>> import datetime 
>>> datetime.datetime.now().month 
8 

datetime.datetime.now()獲取當前時間爲datetime對象和.month屬性打印當前月(如數字)

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

+0

將月份加1不會在十二月份。你可以做'thisMonth%= 12'。 –

+0

@PauloAlmeida,你可以給我代碼的完整語法,我可以做'thisMonth%= 12',這樣這個代碼在12月也可以工作嗎? –

+0

在'thisMonth = int(dt.datetime.now()。month)+ 1'的下方放上確切的一行'thisMonth%= 12'。要清楚的是,如果你對操作不熟悉,那就等於'thisMonth = thisMonth%12',它在12月份將13除以12並返回餘數1。 –

0

通常日以這種方式處理日期和時間的最簡單方法是使用arrow庫。在這種情況下,你可以得到你想要與此代碼是什麼:

>>> import arrow 
>>> arrow.now().shift(months=+1).format('MMMM') 
'September' 
0

如果你想從當前時間一個月後打印日期時間,

可以結合使用datetimedateutil

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) 

那麼你可以使用datetime屬性,如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]))