python 字符串和时间格式(datetime)相互转换-

时间:2020-11-25 17:52:24

2019-03-17 11:00:00格式转化

import datetime # str转时间格式: dd = '2019-03-17 11:00:00' dd = datetime.datetime.strptime(dd, "%Y-%m-%d %H:%M:%S") print(dd,type(dd)) # 时间格式转str: dc = dd.strftime("%Y-%m-%d %H:%M:%S") print(dc,type(dc))

输出:2019-03-17 11:00:00 <class 'datetime.datetime'>
          2019-03-17 11:00:00 <class 'str'>

20190616格式转化

# str转时间格式:
dd = '20190317'
dd = datetime.datetime.strptime(dd, "%Y%m%d")
print(dd,type(dd))

# 时间格式转str:
dc = dd.strftime("%Y%m%d")
print(dc,type(dc))

注:2019-03-17转化成20190317

startDate="2019-06-16"
startDate=startDate.replace("-","")
print(startDate)