Get month from DATETIME in sqlite

前端 未结 7 1236
温柔的废话
温柔的废话 2020-12-01 16:28

I am trying to get extract the month from a DATETIME field in SQLite. month(dateField) does not work as well as strftime(\'%m\', dateStart)

相关标签:
7条回答
  • 2020-12-01 16:31

    I'm guessing you want to get the month as a string. Not the most friendly looking but you probably see the point. Just replace date('now') with your variable.

    select case strftime('%m', date('now')) when '01' then 'January' when '02' then 'Febuary' when '03' then 'March' when '04' then 'April' when '05' then 'May' when '06' then 'June' when '07' then 'July' when '08' then 'August' when '09' then 'September' when '10' then 'October' when '11' then 'November' when '12' then 'December' else '' end
    as month 
    
    0 讨论(0)
  • 2020-12-01 16:33

    I don't understand, the response is in your question :

    select strftime('%m', dateField) as Month ...
    
    0 讨论(0)
  • 2020-12-01 16:37

    I guess strftime('%m', dateStart) is not working for you because dateStart variable is date/datetime type.

    Then you must use:

    strftime('%m', date(dateStart))
    
    0 讨论(0)
  • 2020-12-01 16:48

    This is a solution without all the case when statements. Hopefully it's helpful.

    select substr('JanFebMarAprMayJunJulAugSepOctNovDec', 1 + 3*strftime('%m', date('now')), -3)
    
    0 讨论(0)
  • 2020-12-01 16:51

    Here is my solution that worked for me

    MONTH_DICT={ "Jan" : '01', "Feb" : '02', "Mar" : '03', "Apr" : '04', "May" : '05', "Jun" : '06', "Jul" : '07', "Aug" : '08', "Sep" : '09', "Oct" : 10, "Nov" : 11, "Dec" : 12 }
    
    self.cursor.execute("SELECT * FROM error_log WHERE strftime('%m',Date_column)=?",(MONTH_DICT[query_month],)) 
    
    print('output:', self.cursor.fetchall())
    
    0 讨论(0)
  • 2020-12-01 16:55

    Try using the following:

    select strftime('%m', datetime(datefield, 'unixepoch')) as month from table
    
    0 讨论(0)
提交回复
热议问题