python时间格式datetime、str与date的相互转换在写项⽬的时候经常会⽤到时间格式,以及它们之间的相互转化。
常⽤的⽇期数据格式datetime.datetime, str ,datetime.date
在使⽤的时候先导⼊datetime模块
from datetime import datetime
1.获取当前⽇期
now = w() # 格式为 datetime.datetime
now_date = w().strftime('%Y-%m-%d') # 格式为str
now_time = w().strftime('%Y-%m-%d %H:%M:%S') # 格式为 str
2.从数据库中获取存⼊的⽇期 ,格式为 datetime.date
3.时间数据格式之间的相互转换:
from datetime import datetime
(1)datetime.datetime 转str:
string转date的方法b = w().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
h = str(e)
不能直接转化的,可以通过转化中间介质,然后转化成想要的类型。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论