問題
你的應用程序接受字符串格式的輸入,但是你想將它們轉換為 datetime 對象以便在上面執行非字符串操作。
解決方案
使用Python的標準模塊 datetime 可以很容易的解決這個問題。比如:
1
2
3
4
5
6
7
8
|
>>> from datetime import datetime >>> text = '2012-09-20' >>> y = datetime.strptime(text, '%Y-%m-%d' ) >>> z = datetime.now() >>> diff = z - y >>> diff datetime.timedelta( 3 , 77824 , 177393 ) >>> |
討論
datetime.strptime()
方法支持很多的格式化代碼, 比如 %Y
代表4位數年份, %m
代表兩位數月份。 還有一點值得注意的是這些格式化占位符也可以反過來使用,將日期輸出為指定的格式字符串形式。
比如,假設你的代碼中生成了一個 datetime
對象, 你想將它格式化為漂亮易讀形式后放在自動生成的信件或者報告的頂部:
1
2
3
4
5
6
|
>>> z datetime.datetime( 2012 , 9 , 23 , 21 , 37 , 4 , 177393 ) >>> nice_z = datetime.strftime(z, '%A %B %d, %Y' ) >>> nice_z 'Sunday September 23, 2012' >>> |
還有一點需要注意的是, strptime()
的性能要比你想象中的差很多, 因為它是使用純Python實現,并且必須處理所有的系統本地設置。 如果你要在代碼中需要解析大量的日期并且已經知道了日期字符串的確切格式,可以自己實現一套解析方案來獲取更好的性能。 比如,如果你已經知道所以日期格式是 YYYY-MM-DD
,你可以像下面這樣實現一個解析函數:
1
2
3
4
|
from datetime import datetime def parse_ymd(s): year_s, mon_s, day_s = s.split( '-' ) return datetime( int (year_s), int (mon_s), int (day_s)) |
實際測試中,這個函數比 datetime.strptime()
快7倍多。 如果你要處理大量的涉及到日期的數據的話,那么最好考慮下這個方案!
以上就是Python如何將字符串轉換為日期的詳細內容,更多關于Python字符串轉換為日期的資料請關注服務器之家其它相關文章!
原文鏈接:https://python3-cookbook.readthedocs.io/zh_CN/latest/c03/p15_convert_strings_into_datetimes.html