2013-11-25 24 views
2

我希望看到可與下面的一個類似於不同的打印格式的例子:打印的所有格式,現在()

>>> for d in dir(datetime.datetime.now()): 
... print("\n"+d) 
... print(getattr(datetime.datetime.now(), d)) 

然而,getattr()只返回一個對象的描述,而不是值(在str()包裹,即使):

>>> getattr(datetime.datetime.now(), 'isoformat') 
<built-in method isoformat of datetime.datetime object at 0x020B41A0> 

所以,我怎麼能編造的這相當於用isoformat()被動態補充說:

>>> datetime.datetime.now().isoformat() 
'2013-11-25T15:01:09.075919' 

我必須求助於eval()嗎?

+1

對於日期時間由'dir'顯示的各種方法總的來說對於格式沒有任何作用。 –

回答

4

因爲您沒有將它存儲在任何地方,所以它會打印表示。 getattr實際上返回所需的對象:

>>> import datetime 
>>> isoformat = getattr(datetime.datetime.now(), 'isoformat') 
>>> isoformat() 
'2013-11-25T20:05:57.262055' 

雖然準備幹嗎只是打印字符串表示:

>>> print(isoformat) 
<built-in method isoformat of datetime.datetime object at 0x0000000002F66D50> 

希望這有助於!

+0

不錯,謝謝alKid! – dotancohen

+0

不客氣! – aIKid

1
d = dir(datetime.datetime.now()) 
for i in d: 
    if not i.startswith('_'): # Skip private members 
     m = getattr(datetime.datetime.now(), i) # Get the method 
     print i, # Print the name 
     try:  # some will not work without more info or at all. 
     print m() 
     except Exception, e: 
     print e 

應該給你一個好的開始。在Python 2.6上面的代碼給出了:

astimezone Required argument 'tz' (pos 1) not found 
combine Required argument 'date' (pos 1) not found 
ctime Mon Nov 25 13:23:18 2013 
date 2013-11-25 
day 'int' object is not callable 
dst None 
fromordinal fromordinal() takes exactly 1 argument (0 given) 
fromtimestamp Required argument 'timestamp' (pos 1) not found 
hour 'int' object is not callable 
isocalendar (2013, 48, 1) 
isoformat 2013-11-25T13:23:18.190000 
isoweekday 1 
max 'datetime.datetime' object is not callable 
microsecond 'int' object is not callable 
min 'datetime.datetime' object is not callable 
minute 'int' object is not callable 
month 'int' object is not callable 
now 2013-11-25 13:23:18.195000 
replace 2013-11-25 13:23:18.195000 
resolution 'datetime.timedelta' object is not callable 
second 'int' object is not callable 
strftime Required argument 'format' (pos 1) not found 
strptime strptime() takes exactly 2 arguments (0 given) 
time 13:23:18.198000 
timetuple time.struct_time(tm_year=2013, tm_mon=11, tm_mday=25, tm_hour=13, tm_min=23, tm_sec=18, tm_wday=0, tm_yday=329, tm_isdst=-1) 
timetz 13:23:18.199000 
today 2013-11-25 13:23:18.199000 
toordinal 735197 
tzinfo 'NoneType' object is not callable 
tzname None 
utcfromtimestamp utcfromtimestamp() takes exactly 1 argument (0 given) 
utcnow 2013-11-25 13:23:18.202000 
utcoffset None 
utctimetuple time.struct_time(tm_year=2013, tm_mon=11, tm_mday=25, tm_hour=13, tm_min=23, tm_sec=18, tm_wday=0, tm_yday=329, tm_isdst=0) 
weekday 0 
year 'int' object is not callable 
+0

非常酷,謝謝史蒂夫! – dotancohen