0

I have been trying to programmatically fill a datetime field using values coming from datetime.datetime.now() function.

#I create the temp shp using a URI
URI = 'MultiPolygon?crs=epsg:3857&field=id:integer&field=x:integer&field=y:integer&field=z:integer&field=bx:integer&field=by:integer&field=bz:integer&field=rating:integer&field=timestamp:datetime&index=yes'
# temp shp
mem_layer = QgsVectorLayer(URI, 'temp', 'memory')

# when I try to fill out the timestamp field with a variable now
now = datetime.datetime.now()
# I get an empty or zero value field

It looks like I have to cast the variable first to a string to make it work but in that case I lose the capability to make calculation over the field (I do need to keep track of time to evaluate the "duration" of a specific action triggered by the user)

I tried with the following datatypes with no luck:

date

datetime

real

double

Which datatype should I use when creating the shp in order for it to be filled with that specific value?

0

Sounds like to me you need the full datetime not just the date. If that is the case, then I would recommend you store it as a string, then convert it back to a datetime to do your calculation.

Alternatively, you could parse the datetime object and store all the components in a separate field. So you could store the date in the date field, then store the time as a double using 24hr base.

  • Yes, I wanted to know if I could use the datetime value out-of-the-box (as one would do, for instance in the shell) rather than switching from one cast to another. Is this possible? – mic Feb 20 '14 at 15:10
  • No, as Matt stated shapefiles do not support datetimes. – Jamie Feb 20 '14 at 16:15
2

A Shapefile stores dates in a date field with this format: yyyy-mm-dd. So some string formatting is required.

import datetime

now = datetime.datetime.now()
month = now.month
year = now.year
day = now.day

formatted = "%s-%s-%s" % (year, month, day) 

or

from datetime import datetime

now = datetime.now()
formatted = now.strftime('%Y-%m-%d')
  • Hi Matt, yes, I am aware of the fact that a string value would do it -- now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M %S") -- but I cannot make any calculation out of it, can I? – mic Feb 20 '14 at 15:03

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.