python 日期、时间、字符串相互转换(3)

在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.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

再例如

from datetime import datetime,timedelta

a = datetime.now()
b = datetime.now() - timedelta(days = 7)
print (a>b)  # True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值