python——将字符串转换为日期

python中标准模块datetime能够将字符串转换为日期

python代码

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)

按特定格式输出

java代码

nice_z = datetime.strftime(z, ‘%a %b %d, %y’)

print(nice_z)

datetime.strftime性能很差,下面自己编写一个函数

python代码

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))

Posted in 未分类

发表评论