Python——将字符串转换为日期
程序员文章站
2022-03-22 10:12:25
...
Python中标准模块datetime能够将字符串转换为日期
from datetime import datetime text = '2012-09-20' y = datetime.strptime(text, '%Y-%m-%d') print(y) z = datetime.now() diff = z - y print(diff)
按特定格式输出
nice_z = datetime.strftime(z, '%A %B %d, %Y') print(nice_z)
datetime.strftime性能很差,下面自己编写一个函数
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))