4

How can I convert unix timestamp to qt time type using qgis field calculator? I would like to avoid importing my table into excel and convert the timestamp to qt time type.

4

This is fairly easy to do using the Field calculator and a simple custom function. The result is a string, which you can coerce to a proper time/date class later (e.g. for some proper date/time calculations), or extend the script to do that for you.

Open Field calculator and click the Function editor tab. You can create a new New file or extend an existing one with the following few lines of (Python) code:

"""
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 *
import time

@qgsfunction(args='auto', group='Custom')
def fromSecToDate(value1, feature, parent):
    outtime = time.gmtime(value1)
    outtime = time.strftime("%d-%m-%Y", outtime)
    return outtime

It should look like this in 2.18.3.

enter image description here

Once you're done, do not forget to hit the Load button. Now switch to Expression tab and find fromSecToDate function under the Custom group (as defined in the script, feel free to modify). Don't forget to properly name your variables and set the Output field type to Text (string).

enter image description here

To be able to coerce to a date format, you'll need to modify the above script by changing the order of units: year-month-day

time.strftime("%d-%m-%Y", outtime)

and then in the Expression tab creating a new Date type field using

to_date(fromSecToDate("yourvariable"))
3

if not availble you can always create your own convertion function:

http://nathanw.net/2012/11/10/user-defined-expression-functions-for-qgis/

and should be good to share it in some place or to propose to insert in the expression library

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.