如何将datetime.datetime转换成datetime.date?

How to convert datetime.datetime to datetime.date?

从我的 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,但仍然无效。似乎无法弄清楚这里的问题是什么。

试试这个

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')

注意:使用 'HH' 表示 24 小时制,'hh' 表示 12 小时制。

要强制您的查询吐出您想要的 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