Python 代碼閱讀合集介紹:為什么不推薦Python初學(xué)者直接看項(xiàng)目源碼
本篇閱讀的代碼實(shí)現(xiàn)了將datetime
對(duì)象轉(zhuǎn)化為ISO 8601
字符串,并將其還原回datetime
對(duì)象的功能赞草。
本篇閱讀的代碼片段來(lái)自于30-seconds-of-python讹堤。
to_iso_date
from datetime import datetime
def to_iso_date(d):
return d.isoformat()
# EXAMPLES
print(to_iso_date(datetime(2020, 10, 25))) # 2020-10-25T00:00:00
to_iso_date
函數(shù)接收一個(gè)datetime
對(duì)象,返回ISO 8601
標(biāo)準(zhǔn)的日期和時(shí)間字符串厨疙。
函數(shù)直接使用datetime.isoformat()
進(jìn)行轉(zhuǎn)化洲守。
from_iso_date
from datetime import datetime
def from_iso_date(d):
return datetime.fromisoformat(d)
# EXAMPLES
print(from_iso_date('2020-10-28T12:30:59.000000')) # 2020-10-28 12:30:59
from_iso_date
函數(shù)接收一個(gè)ISO 8601
規(guī)范的日期和時(shí)間字符串,返回一個(gè)datetime.datetime
對(duì)象沾凄。
函數(shù)直接使用datetime
對(duì)象的fromisoformat()
方法將日期字符串轉(zhuǎn)化為datetime
對(duì)象梗醇。
實(shí)際上該函數(shù)并不支持解析任意ISO 8601
字符串。它是作為datetime.isoformat()
的逆操作撒蟀。 在第三方包dateutil
中提供了一個(gè)更完善的ISO 8601
解析器dateutil.parser.isoparse
叙谨。