python中strftime和strptime函数

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实例的格式是固定的

猜你喜欢

转载自www.cnblogs.com/mghhzAnne/p/11429447.html