开发者

SQL statement to convert date-time format in some columns

I have an SQLite datab开发者_C百科ase in which some columns are date-time strings with the format 1/2/2000 3:45:56 am.

Is there an SQL statement which can convert these values to strings with an ISO-8601-like format (2000-01-02 03:45:56)?

(One possible non-SQL way to do this would be to export the database as a CSV file, and use Python, with its csv and datetime modules, to parse the columns.)


SQL As Understood By SQLite - Date And Time Functions.


Converting the other way would be easy: You could use strftime. But this requires the date to be in ISO 8601 format (or a Julian or Unix date) to begin with.

You could do it in SQL with string manipulation, but it would be horribly complex. The easiest way would be to make a user-defined function.

def fix_timestamp(timestamp):
    return datetime.datetime.strptime(timestamp, '%m/%d/%Y %I:%M:%S %p') \
           .strftime('%Y-%m-%d %H:%M:%S')

db = sqlite3.connect('...')
db.create_function('FixTimestamp', 1, fix_timestamp)

Then you can do UPDATE TheTable SET TheColumn = FixTimestamp(TheColumn).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜