python⽇期、时间、字符串相互转换
在python中,⽇期类型date和⽇期时间类型dateTime是不能⽐较的。
(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.573139print(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 print(str_p,type(str_p)) #2019-01-30 (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 python3import datetimestr_p = '2019-01-30'
date_p = datetime.datetime.strptime(str_p,'%Y-%m-%d').date()print(date_p,type(date_p)) # 2019-01-30 另外dateTime类型和date类型可以直接做加1减1这种操作
#!/usr/bin/env python3import 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-30print(yestoday)# 2019-01-29print(tomorrow)# 2019-01-31