Thursday, 28 January 2016

qgis - How to convert a string field to a date field


I have a layer with points which represent the fatal road accidents and the field "dates_14_D" contains their date but its type is string. I would like to convert this string field to date field but the OK button is inactive. What's the problem? I use QGis. Look the below pictureenter image description here



Answer



I'm surprised I haven't seen this before. Maybe I'm overlooking something obvious :)


Although you're using a different locale to me, you're using the same date format as I do in the UK, dd/MM/yyyy. I get a slightly different error (on QGIS 2.16.1) but it doesn't like that date format.


You can get around this by creating a short python script in the function editor tab of the expression editor.




  • Go into the function editor tab in the expression editor

  • Create a new function ("New file" button)

  • paste the following into the code window. You may get indentation errors, so manually re-indent with spaces if needed

  • click on "Load" button to save the changes

  • switch back to the expression tab

  • look under the python heading, should now see a function called parse_date_dmy




from qgis.core import *
from qgis.gui import *

from PyQt4.QtCore import QDate

@qgsfunction(args="auto", group='Python')
def parse_date_dmy(fromval, feature, parent):
return QDate.fromString(fromval, 'dd/MM/yyyy')

You can then enter an expression like so, using your field name :-


parse_date_dmy("mydate") 

If all is well, you should see something like this...



enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...