Neau Adrien Neau Adrien - 8 months ago 34
Python Question

Poblem with strftime (python)

I try to send data on Mosquitto Broker and add this same data on SQLite
This is my script:

# -*- coding: utf-8 -*-
import sqlite3
import logging

class Photos:
def __init__(self):
#Connection a la basse de donnees sqlite3
self.db = sqlite3.connect('/home/pi/FlowerPower.db')
#Preparation d'un objet cursor qui va executer les futures requetes SQL sur la base de donnees
self.cursor = self.db.cursor()

logging.basicConfig(filename='subscribeFP.log',level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

def traitement(self, msg, numSonde):
#Convertit le message poste par le publisher de byte a string
queryArgs = str(msg.payload)
#Variable nom de la sonde
nomSonde = str(numSonde[2])
#Prepare la requete SQL pour la table photo
queryText = "INSERT INTO photos(sonde, date, photos) VALUES (?, ?, ?)", (nomSonde, strftime('%%d-%%m-%%Y %%H:%%%M:%%S','now','localtime'), queryArgs)
#Execute la requete SQL sur la BDD
#Commit pour etre sur que la requete SQL est effectuee
#Code d'exception
except sqlite3.Error as e:
self.logging.error('Erreur Sqlite3: ' + str(e))
#Retour en arrière si il y a une erreur (proprietes ACID)

When I send data with a mosquitto_pub,
I have this error:

File "/usr/lib/python3/dist-packages/", line 720, in loop
rc = self.loop_read(max_packets)
File "/usr/lib/python3/dist-packages/", line 961, in loop_read
rc = self._packet_read()
File "/usr/lib/python3/dist-packages/", line 1360, in _packet_read
rc = self._packet_handle()
File "/usr/lib/python3/dist-packages/", line 1775, in _packet_handle
return self._handle_publish()
File "/usr/lib/python3/dist-packages/", line 1888, in _handle_publish
self.on_message(self, self._userdata, message)
File "", line 37, in on_message
photos.traitement(msg, numSonde)
File "/home/pi/", line 22, in traitement
queryText = "INSERT INTO photos(sonde, date, photos) VALUES (?, ?, ?)", (nomSonde, strftime('%%d-%%m-%%Y %%H:%%%M:%%S','now','localtime'), queryArgs)
NameError: global name 'strftime' is not defined

I don't understand why i have this error and i have already try to add: "from datetime importe datetime"
My other script, run with strftime but there are not this problem...
Somebody can help me, please?


Like the message says, you haven't defined strftime, you've only defined datetime.

strftime is a method of a datetime object. However, you seem to be calling it as a standalone function, passing it some strings: that's not at all how it works. I'm not sure what you are trying to do, but it looks like you want to get the current time and format that. So, you need to actually call the relevant methods:'%d-%m-%Y %H:%M:%S')

I'm also not sure what 'localtime' is doing in your code, or why you doubled the percent signs.