怎么把datetime.datetime转换成datetime.date?

时间:2020-10-22 11:25:26

标签: mysql python-2.7 datetime

从我的sql查询中,我得到的输出为datetime.datetime(2020, 9, 22, 0, 0)

query = '''SELECT checkin_date FROM `table1`
WHERE checkin_date BETWEEN %s AND %s'''

cursor.execute(query,(startDate, endDate)
results = cursor.fetchall()

#results:
#[(datetime.datetime(2020, 9, 22, 0, 0), datetime.datetime(2020, 9, 24, 0, 0))]

for res in results:
   ## When I print type I get correct result
   print(type(res[0]) ## <type 'datetime.datetime'>

   ##when I compare with another datetime.date (currentDate variable)
   if res[0] < currentDate:
   ## I get error `TypeError: can't compare datetime.datetime to datetime.date` *which is expected*

   ## But when I use .date()
   if res[0].date() < currentDate:
   ## I get `TypeError: can't compare datetime.date to unicode`

我尝试将currentDate转换为datetime.datetime,但仍然无法正常工作。似乎无法找出问题所在。

2 个答案:

答案 0 :(得分:1)

尝试一下

splitting a datetime column into year, month and week

SELECT        Year(checkin_date), Month(Checkin_date), Day(Checkin_date), 
FORMAT(GETDATE(),'HH'), FORMAT(GETDATE(),'mm')
FROM            table1
WHERE        (CAST(checkin_date AS DATE) BETWEEN '2018-01-01' AND '2020-01-01')

注意:24小时格式使用“ HH”,12小时格式使用“ hh”。

答案 1 :(得分:1)

要强制您的查询吐出您想要的date format,请将其更改为:

     SELECT DATE_FORMAT(checkin_date, '%Y-%c-%d') 
       FROM table1
      WHERE DATE(checkin_date) BETWEEN %s AND %s

要使其能够使用checkin_date列上的索引,请将其更改为此。

     SELECT DATE_FORMAT(checkin_date, '%Y-%c-%d') 
       FROM table1
      WHERE checkin_date >= DATE(%s)
        AND checkin_date < DATE(%s) + INTERVAL 1 DAY