Reformat dates in column

后端 未结 2 698
走了就别回头了
走了就别回头了 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)')
    
    >>> cur.execute('INSERT INTO EXAMPLE VALUES ("1/1/2014")')
    
    >>> 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)')
    
    

提交回复
热议问题