I have a table with one of the fields named Date_Time. The features are like 21-5-2016 14:47:00 (field type is string).
I want to extract the dates and add them to a new field with the Conversion function "to_date" in the Field Calculator.

I tried but the conversion has no result. The new field stays empty. Whether I giving the new field the type "string", "date", etc. and changing the Date_Time field type into date as well (with refractor). Nothing works. Can anyone help?


1 Answer 1


As @AndreJ mentioned in his comment, the to_date function works with YYYY-MM-DD format. But here's a couple of options:

  1. Only extract the date and add it to a new string field using:

    left("date_time", strpos("date_time", ' '))

    The above expression extracts all characters to the left of the first 'space' it encounters.

  1. Create a python function in your Field Calculator to convert your values to the YYYY-MM-DD format which can be stored in a date field. You can do this by going to the Field Calculator, click the Function Editor tab and enter the following code:

    from qgis.core import *
    from qgis.gui import *
    import datetime
    @qgsfunction(args='auto', group='Custom')
    def convert(field, feature, parent):
        return datetime.datetime.strptime(field, "%d-%m-%Y %H:%M:%S").strftime("%Y-%m-%d")

    Function editor

    When you insert the code, click the Load button then go back to the Expressions tab and set the relevant options to create a new field. Then use an expression which calls the function and insert the name of your field (e.g. "date_time"):



    Then click OK and hopefully your new field will contain the dates:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.