首页  >  文章  >  后端开发  >  如何把字符串转化成时间

如何把字符串转化成时间

anonymity
anonymity原创
2019-05-25 16:13:4328964浏览

在python中,日期、时间、字符串的相互转换。

如何把字符串转化成时间

(1)可以将dateTime转换为date,date不能直接转换为dateTime

import datetime
dateTime_p = datetime.datetime.now()  
date_p = dateTime_p.date() 
print(dateTime_p) #2019-01-30 15:17:46.573139
print(date_p) #2019-01-30

(2)日期类型date转换为字符串str

#!/usr/bin/env python3
import datetime
date_p = datetime.datetime.now().date()
str_p = str(date_p)
print(date_p,type(date_p)) #2019-01-30 <class &#39;datetime.date&#39;>
print(str_p,type(str_p)) #2019-01-30 <class &#39;str&#39;>

(3)字符串类型str转换为dateTime类型

import datetime
str_p = &#39;2019-01-30 15:29:08&#39;
dateTime_p = datetime.datetime.strptime(str_p,&#39;%Y-%m-%d %H:%M:%S&#39;)
print(dateTime_p) # 2019-01-30 15:29:08

(4)dateTime类型转为str类型

import datetime
dateTime_p = datetime.datetime.now()
str_p = datetime.datetime.strftime(dateTime_p,&#39;%Y-%m-%d&#39;)
print(dateTime_p) # 2019-01-30 15:36:19.415157

(5)字符串类型str转换为date类型

#!/usr/bin/env python3
import datetime
str_p = &#39;2019-01-30&#39;
date_p = datetime.datetime.strptime(str_p,&#39;%Y-%m-%d&#39;).date()
print(date_p,type(date_p)) # 2019-01-30 <class &#39;datetime.date&#39;>

另外dateTime类型和date类型可以直接做加1减1这种操作

#!/usr/bin/env python3
import datetime
# today = datetime.datetime.today()
today = datetime.datetime.today().date()
yestoday = today + datetime.timedelta(days=-1)
tomorrow = today + datetime.timedelta(days=1)
print(today) # 2019-01-30
print(yestoday)# 2019-01-29
print(tomorrow)# 2019-01-31

以上是如何把字符串转化成时间的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn