2014-02-12 39 views
21

我想設置一個變量來等於今天的日期。如何在Python/Pandas中將變量設置爲「今日」日期

我看這件事,發現相關文章:

Set today date as default value in the model

然而,這並沒有特別的回答我的問題。

我使用的建議:

dt.date.today 

但經過

import datetime as dt  
date = dt.date.today 
print date 
<built-in method today of type object at 0x000000001E2658B0> 

Df['Date'] = date 

我沒有得到什麼,我其實是想這是今天的日期乾淨的日期格式...在月/日/年。

如何創建今天的變量以便我在DataFrame中輸入該變量?

+5

你只需要調用該方法。 'date = dt.date.today()' – mhlester

+3

請注意,當第二天到來時,該日期對象仍將代表前一天。 – user2357112

+0

我沒有意識到我需要()。 – Alexis

回答

34

如果你想代替datetime對象的字符串mm/dd/yyyy,您可以使用strftime(字符串格式時間):

>>> dt.datetime.today().strftime("%m/%d/%Y") 
        #^note parentheses 
'02/12/2014' 
+5

http://stackoverflow.com/help/someone-answers – jonrsharpe

+0

大聲笑@你的評論。 –

+0

@JacksonTale我認爲跟着一個*「謝謝」*從OP - 一整年,並沒有接受:'( – jonrsharpe

2

我得到了同樣的問題,所以嘗試了這麼多的事情 但最後是這樣的解決方案。

import time 

print (time.strftime("%d/%m/%Y")) 
+1

歡迎來到SO,請在您的答案中使用代碼標記 –

44

你提到你正在使用熊貓(在你的標題)。如果是這樣,也沒有必要使用一個外部庫,你可以使用to_datetime

>>> pandas.to_datetime('today') 
Timestamp('2015-10-14 00:00:00') 

這在午夜,總是會返回今天的日期,而不管實際時間(但你猜怎麼着爭論now都行)。在Python3 +

+0

不格式化與新的方式版本:( –

+3

'pd.to_datetime('now')'獲得時間以及 – pshep123

+0

整潔,但似乎默認情況下是UTC時區 – wordsforthewise

2

簡單的解決方案:

import time 


todaysdate = time.strftime("%d/%m/%Y") 

#with '.' isntead of '/' 
todaysdate = time.strftime("%d.%m.%Y") 
2
import datetime 
def today_date(): 
    ''' 
    utils: 
    get the datetime of today 
    ''' 
    date=datetime.datetime.now().date() 
    date=pd.to_datetime(date) 
    return date 
Df['Date'] = today_date() 

這可能在大熊貓dataframes安全使用。

2

使用熊貓:pd.Timestamp("today").strftime("%m/%d/%Y")

相關問題