2015-03-06 7 views
13

पर इतने सवाल 904928 (Python strftime - date without leading 0?) रयान ने उत्तर दिया:"% -d", या "% -e" प्रमुख स्थान या शून्य को क्यों हटाता है?

Actually I had the same problem and I realised that, if you add a hyphen between the % and the letter, you can remove the leading zero.

For example %Y/%-m/%-d.

मैं एक ही समस्या का सामना करना पड़ा और कहा कि एक महान समाधान था, लेकिन, क्यों यह इस तरह व्यवहार करता है?

>>> import datetime 
>>> datetime.datetime(2015, 3, 5).strftime('%d') 
'05' 

>>> datetime.datetime(2015, 3, 5).strftime('%-d') 
'5' 

# It also works with a leading space 
>>> datetime.datetime(2015, 3, 5).strftime('%e') 
' 5' 

>>> datetime.datetime(2015, 3, 5).strftime('%-e') 
'5' 

# Of course other numbers doesn't get stripped 
>>> datetime.datetime(2015, 3, 15).strftime('%-e') 
'15' 

मुझे इसके बारे में कोई दस्तावेज नहीं मिल रहा है? ->python datetime docs/python string operations

ऐसा लगता है कि यह विंडोज मशीनों पर काम नहीं करता है, ठीक है, मैं विंडोज़ का उपयोग नहीं करता लेकिन यह जानना दिलचस्प होगा कि यह क्यों काम नहीं करता है?

+1

मेरे Windows पर केवल अपना पहला उदाहरण का निर्माण बिना किसी त्रुटि के काम करता है। बाकी का परिणाम 'ValueError: अवैध प्रारूप स्ट्रिंग' में होता है। [यह सवाल] (http://stackoverflow.com/questions/10807164/python-time-formatting- अलग-अलग- विन्डोज़) मानक/पोर्टेबल निर्देश बनाम प्लेटफ़ॉर्म-विशिष्ट "एन्हांसमेंट्स" के संबंध में आपके बारे में कुछ प्रकाश डाल सकता है। – jedwards

+0

तो यह प्रत्येक ओएस के libc कार्यान्वयन पर निर्भर करता है। धन्यवाद! यूनिक्स सिस्टम पर आम तौर पर उन उदाहरणों के बारे में कोई संकेत कैसे काम करता है? – Mathias

उत्तर

16

Python datetime.strftime() delegates to C strftime() function that is platform-dependent:

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

Glibc notes for strftime(3):

- (dash) Do not pad a numeric result string.

परिणाम मेरे Ubuntu मशीन पर:

>>> from datetime import datetime 
>>> datetime.now().strftime('%d') 
'07' 
>>> datetime.now().strftime('%-d') 
'7' 
संबंधित मुद्दे