2012-05-16 134 views

回答

271

您可以使用strftime來幫助您格式化您的日期。

例如,

import datetime 
t = datetime.datetime(2012, 2, 23, 0, 0) 
t.strftime('%m/%d/%Y') 

將產生:

'02/23/2012' 

有關格式信息,請參閱here

+2

非常用於'DateTimeField'或'DateField'在Django有用。謝謝 – erajuan

+0

使用't = datetime.datetime.now()'使用當前日期 – gizzmole

+0

據我可以從文檔中看出,無法返回非零填充日期,即'2/23/2012'。 –

10

你可以使用簡單的字符串格式化方法:

>>> dt = datetime.datetime(2012, 2, 23, 0, 0) 
>>> '{0.month}/{0.day}/{0.year}'.format(dt) 
'2/23/2012' 
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year) 
'2/23/2012' 
+1

類似地,你可以做''{:%Y-%m-%d%H:%M}'格式(datetime(2001,2,3,4,5))''。在pyformat.info查看更多 – mway

81

datedatetime對象(和time以及)支持mini-language to specify output,有兩種方法來訪問它:

  • 直接調用方法:dt.strftime('format here');和
  • 新格式的方法:'{:format here}'.format(dt)

所以,你的例子可能看起來像:

dt.strftime('%m/%d/%Y') 

'{:%m/%d/%Y}'.format(dt) 

爲了完整性:您也可以直接訪問的屬性的對象,但你只能得到的數字:

'%s/%s/%s' % (dt.month, dt.day, dt.year) 

學習迷你語言所花費的時間是值得的。


供參考,在這裏是在小型語言使用的代碼:

  • %a平日的語言環境的縮寫名稱。
  • %A工作日爲區域設置的全名。
  • %w平日爲十進制數字,其中0表示星期日,6表示星期六。
  • %d當月的一天爲零填充十進制數。
  • %b月份爲區域設置的縮寫名稱。
  • %B月份作爲語言環境的全名。
  • %m月爲零填充十進制數。 01,...,
  • %y沒有世紀的一年作爲零填充十進制數。 00,...,99
  • %Y以十進制數表示的世紀。 1970,1988,2001,2013
  • %H小時(24小時制)作爲零填充十進制數。 00,...,23
  • %I小時(12小時制)作爲零填充十進制數。 01,...,12
  • %p Locale相當於AM或PM。
  • %M分鐘爲零填充十進制數字。 00,...,59
  • %S第二個作爲零填充的十進制數。 00,...,59
  • %f微秒作爲十進制數,左側填零。 000000,...,999999
  • %z UTC形式偏移+ HHMM或-HHMM(空if幼稚),+0000,-0400,1030
  • %Z時區名稱(空如果幼稚),UTC, EST,CST
  • %j一年中的一天爲零填充十進制數。 001,...,366
  • %U一年中的星期數(星期日是第一個)作爲零填充十進制數。
  • %W年的週數(星期一是第一個)作爲十進制數。
  • %c區域設置的適當日期和時間表示。
  • %x區域設置的相應日期表示。
  • %X區域設置的適當時間表示。
  • %%字面'%'字符。
+1

賞金在這裏總結得很好 – tinySandy

1

字符串連接,str.join,可用於構建字符串。

d = datetime.now() 
'/'.join(str(x) for x in (d.month, d.day, d.year)) 
'3/7/2016' 
14

另一種選擇:

import datetime 
now=datetime.datetime.now() 
now.isoformat() 
# ouptut --> '2016-03-09T08:18:20.860968' 
0

可以時間值轉換爲字符串。 published_at="{}".format(self.published_at)

-2

通過直接處理日期時間對象的組件,可以將日期時間對象轉換爲字符串。

from datetime import date 

myDate = date.today()  
#print(myDate) would output 2017-05-23 because that is today 
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer 
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)  
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as 
# an integer i change it to a string with str() and it is added to the "5/" 
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string. Now we have "5/23/2017" as 
# a string. The final line prints the string. 

print(dateStr) 

輸出 - > 2017年5月23日

+0

請使用[編輯]鏈接來解釋此代碼的工作原理,而不只是給出代碼,因爲解釋更有可能幫助未來的讀者。另見[回答]。 [源(http://stackoverflow.com/users/5244995) –

相關問題