I have a data set with hours such as 8am to 6pm. I would like to convert this from 12 hour clock format into 24 hour clock format. So instead of "8am to 6pm" I would want "08:00-18:00" Does anyone know how to do this in QGIS, using Field Calculator or using a script with Python?

I would be very thankful if someone could help me with this.


You can create a custom function in the Field Calculator that will do this for you. I created a function converter() which worked to convert the text "8am to 6pm" into the text "08:00-18:00":

Define new functions using @qgsfunction. feature and parent must always be the
last args. Use args=-1 to pass a list of values as arguments

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

@qgsfunction(args='auto', group='Custom')
def converter(value1, feature, parent):
    return datetime.strptime(value1.split(" to ")[0],'%I%p').strftime('%H:%M') + "-" + datetime.strptime(value1.split(" to ")[1],'%I%p').strftime('%H:%M')

For some reason in QGIS 2.18 it would only take a single-line function, so I have had to stick it all in one line. What it does is split on the " to " portion of the text input, then formats "8am" and "6pm" into 24 hour time using the strptime/strftime.

After saving this in the run this in the "Function Editor" within a new file, navigate back to the "Expression" tab and run: converter("YourFieldName").

  • Many many thanks for your answer. That's great. Now I'm trying to convert 'Monday to Saturday' to 'Mon-Sat'. I've tried to follow the same using the module 'datetime' and changing %I%p for %A and %a but I get 'Mon-Mon' and I don't really know why. I would really appreciate some help. Thanks – Senda Feb 26 at 16:12
  • Probably best executed with gsub(), such as: gsub(“Monday”,”Mon”,your_string) and gsub(“ to ”, “-“,yourstring). – Jackson Mar 2 at 23:04

What you can do is to export the attribute table to excel, then to search and replace with Excel (or an other software) and finally to join the table. There is maybe a simpler solution, but if you have to change just a data set, you won't lose lots of time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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