
Python 代码阅读合集介绍:为什么不推荐Python初学者直接看项目源码
本篇阅读的代码实现了将datetime对象转化为ISO 8601字符串,并将其还原回datetime对象的功能。
本篇阅读的代码片段来自于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函数接收一个datetime对象,返回ISO 8601标准的日期和时间字符串。
函数直接使用datetime.isoformat()进行转化。
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函数接收一个ISO 8601规范的日期和时间字符串,返回一个datetime.datetime对象。
函数直接使用datetime对象的fromisoformat()方法将日期字符串转化为datetime对象。
实际上该函数并不支持解析任意ISO 8601字符串。它是作为datetime.isoformat()的逆操作。 在第三方包dateutil中提供了一个更完善的ISO 8601解析器dateutil.parser.isoparse。