在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 'datetime.date'> print(str_p,type(str_p)) #2019-01-30 <class 'str'>
(3)字串型別str轉換為dateTime型別
import datetime str_p = '2019-01-30 15:29:08' dateTime_p = datetime.datetime.strptime(str_p,'%Y-%m-%d %H:%M:%S') 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,'%Y-%m-%d') print(dateTime_p) # 2019-01-30 15:36:19.415157
(5)字串型別str轉換為date類型
#!/usr/bin/env python3 import datetime str_p = '2019-01-30' date_p = datetime.datetime.strptime(str_p,'%Y-%m-%d').date() print(date_p,type(date_p)) # 2019-01-30 <class 'datetime.date'>
另外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中文網其他相關文章!