2010-10-18 87 views
62

我怎麼能顯示當前的時間爲:在Python中,如何顯示當前時間可讀格式

12:18PM EST on Oct 18, 2010 
在Python

。謝謝。

+4

對不起,我認爲這將有助於在網站上擴展問題和答案的數據庫。之前沒有人問過這個問題。 – ensnare 2010-10-18 17:57:39

+0

@ensnare:其中每一個似乎已經回答了這個問題:http://stackoverflow.com/search?q=%5Bpython%5D+time+format。你是否暗示你的問題有一些獨特之處?如果是這樣,是什麼讓你的問題獨特? – 2010-10-18 19:35:39

+1

可能重複的[Python:日期,時間格式化](http://stackoverflow.com/questions/2487109/python-date-time-formatting) – 2010-10-18 19:36:44

回答

67

首先是快速和骯髒的方式,和第二的精確的方式(識別白天儲蓄或不)。

import time 
time.ctime() # 'Mon Oct 18 13:35:29 2010' 
time.strftime('%l:%M%p %Z on %b %d, %Y') # ' 1:36PM EDT on Oct 18, 2010' 
time.strftime('%l:%M%p %z on %b %d, %Y') # ' 1:36PM EST on Oct 18, 2010' 
+0

'%z'產生偏移,例如'-0400'。 '%Z'自動爲您提供當前時區名稱(或縮寫)。 Python不支持'%l',您可以改用'%I'。 – jfs 2013-12-14 19:30:35

+0

%Z給我「東部時區」我怎樣才能得到'est'或'EST'的縮寫 – 2017-11-14 19:24:29

1

看看由http://docs.python.org/library/time.html

提供的設施,讓您有幾個轉換函數存在。

編輯:看到datetime(http://docs.python.org/library/datetime.html#module-datetime)也爲更多的OOP樣的解決方案。上面鏈接的time庫有點必要。

5

你可以這樣做:

>>> from time import gmtime, strftime 
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) 
'Thu, 28 Jun 2001 14:17:15 +0000' 

上的%代碼的完整文檔是在http://docs.python.org/library/time.html

相關問題