One - One Code All

Blog Content

python的时间格式datetime、str与date的相互转换

Python   2016-08-16 20:38:47


常用的日期数据格式datetime.datetime, str ,datetime.date


在使用的时候先导入datetime模块


from datetime import datetime


1.获取当前日期


now_date = datetime.now().strftime('%Y-%m-%d')    # 格式为str


now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')    # 格式为 datetime.datetime


2.时间数据格式之间的相互转换:


from datetime import datetime


(1)datetime.datetime 转str:


 b = datetime.now().strftime('%Y-%m-%d')


(2)str 转datetime.datetime


 d = datetime.strptime(b, '%Y-%m-%d')  # strptime()内参数必须为string格式


(3)str 转 datetime.date


 先将str转datetime,再转datetime.date

 e = datetime.date(d) # date()内参数需要datetime.datetime型


(4)datetime.date转str

e = datetime.date(d)

h = str(e)



上一篇:MongoDB查询小结 - find【查询条件$lt $lte $gt $gte】
下一篇:python中collections.defaultdict()的使用

The minute you think of giving up, think of the reason why you held on so long.