Reformat dates in column

后端 未结 2 695
走了就别回头了
走了就别回头了 2021-01-25 04:15

I have some data in an SQLite DB of the form:

id  column1  date
111 280 1/1/2014
114 275 1/2/2014

The date field is of type TEXT. I\'ve been ma

相关标签:
2条回答
  • 2021-01-25 04:43

    Without any frills such as exception handling!

    This approach is slightly simpler because strptime doesn't mind about presence or absence of leading zeroes in days and months.

    >>> from datetime import datetime
    >>> import sqlite3
    >>> con = sqlite3.connect(':memory:')
    >>> cur = con.cursor()
    >>> cur.execute('CREATE TABLE EXAMPLE (date_column text)')
    <sqlite3.Cursor object at 0x00000000038D07A0>
    >>> cur.execute('INSERT INTO EXAMPLE VALUES ("1/1/2014")')
    <sqlite3.Cursor object at 0x00000000038D07A0>
    >>> def transformDate(aDate):
    ...     tempDate = datetime.strptime(aDate, '%d/%m/%Y')
    ...     return tempDate.strftime('%Y-%m-%d')
    ... 
    >>> transformDate('1/1/2014')
    '2014-01-01'
    >>> con.create_function('transformDate', 1, transformDate)
    >>> cur.execute('UPDATE EXAMPLE SET date_column = transformDate(date_column)')
    <sqlite3.Cursor object at 0x00000000038D07A0>
    
    0 讨论(0)
  • 2021-01-25 04:54

    Your current date format has four possible forms:

    m/d/yyyy
    m/dd/yyyy
    mm/d/yyyy
    mm/dd/yyyy
    

    To rearrange the fields, extract them with substr() and then combine them again.

    It might be possible to determine the positions of the slashes with instr(), but for a one-off conversion, just using four queries is simpler:

    UPDATE MyTable
    SET date = substr(date, 6, 4) || '-' ||
               substr(date, 1, 2) || '-' || '0' ||
               substr(date, 4, 1)
    WHERE date LIKE '__/_/____';
    
    -- this is mm/d/yyyy; similarly for the other forms, modify positions and zeros
    
    0 讨论(0)
提交回复
热议问题