python中strftime和strptime函数

匿名 (未验证) 提交于 2019-12-02 22:51:30

strftime和strptime函数均来自包datetime

from datetime import *

strftime:

将datetime包中的datetime类,按照入参格式生成字符串变量

from datetime import * currenttime=datetime.now()  #生成当前时间的datetime类实例 print('type of currenttime', type(currenttime)) print(currenttime) cur=currenttime.strftime('%Y_%m_%d-%H-%M-%S') print('type of cur', type(cur)) print(cur)

输出

type of currenttime <class 'datetime.datetime'> 2019-08-29 14:01:39.973547 type of cur <class 'str'> 2019_08_29-14-01-39

strptime:

将字符串根据其格式,提取所含时间,并生成datetime类实例

from datetime import * strdate='2019:08:29:09-00-00' strdatetime=datetime.strptime(strdate,'%Y:%m:%d:%H-%M-%S') print('type of strdatetime:',type(strdatetime),':',strdatetime)

输出

type of strdatetime: <class 'datetime.datetime'> : 2019-08-29 09:00:00

注意:strptime中的第二个参数是输入字符串的格式,而不是出参格式,datetime实例的格式是固定的

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!