問題
你的應(yīng)用程序接受字符串格式的輸入,但是你想將它們轉(zhuǎn)換為 datetime 對象以便在上面執(zhí)行非字符串操作。
解決方案
使用Python的標(biāo)準(zhǔn)模塊 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位數(shù)年份, %m
代表兩位數(shù)月份。 還有一點(diǎn)值得注意的是這些格式化占位符也可以反過來使用,將日期輸出為指定的格式字符串形式。
比如,假設(shè)你的代碼中生成了一個 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' >>> |
還有一點(diǎn)需要注意的是, strptime()
的性能要比你想象中的差很多, 因為它是使用純Python實(shí)現(xiàn),并且必須處理所有的系統(tǒng)本地設(shè)置。 如果你要在代碼中需要解析大量的日期并且已經(jīng)知道了日期字符串的確切格式,可以自己實(shí)現(xiàn)一套解析方案來獲取更好的性能。 比如,如果你已經(jīng)知道所以日期格式是 YYYY-MM-DD
,你可以像下面這樣實(shí)現(xiàn)一個解析函數(shù):
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)) |
實(shí)際測試中,這個函數(shù)比 datetime.strptime()
快7倍多。 如果你要處理大量的涉及到日期的數(shù)據(jù)的話,那么最好考慮下這個方案!
以上就是Python如何將字符串轉(zhuǎn)換為日期的詳細(xì)內(nèi)容,更多關(guān)于Python字符串轉(zhuǎn)換為日期的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://python3-cookbook.readthedocs.io/zh_CN/latest/c03/p15_convert_strings_into_datetimes.html