
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。