Alvin Wee
Alvin Wee

Reputation: 195

TypeError: a float is required PYTHON

My current python script:

import ftplib
import hashlib
import httplib
import pytz
from datetime import datetime
import urllib
from pytz import timezone
import os.path, time
import glob

def ftphttp():
 dataset_path='Desktop'   
 files = glob.glob(dataset_path+"/images/*.png")   
 ts = files.sort(key=os.path.getmtime)
 dt = datetime.fromtimestamp(ts, pytz.utc)
 timeZone= timezone('Asia/Singapore')
 localtime = dt.astimezone(timeZone).isoformat()

 cam = "002"

 lscam = localtime + cam
 ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
 ftp.cwd('/var/www/html/image')

 m=hashlib.md5()
 m.update(lscam)
 dd=m.hexdigest()

 for image in glob.glob(os.path.join('Desktop/images/*.png')):
  with open(image, 'rb') as file:
    ftp.storbinary('STOR '+dd+ '.png', file)

 x = httplib.HTTPConnection('localhost', 8086)
 x.connect()
 f = {'ts' : localtime}
 x.request('GET','/camera/store?cam='+cam+'&'+urllib.urlencode(f)+'&fn='+dd)
 y = x.getresponse()
 z=y.read()
 x.close()
 ftp.quit()

The trackback:

Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
 ftphttp()
File "/home/kevin403/Testtimeloop.py", line 17, in ftphttp
 dt = datetime.fromtimestamp(ts, pytz.utc)
TypeError: a float is required

I trying to get a list of files in a folder to get their modified timestamp and store it in a database. But i can't seem to do it. Anybody got an idea on how to do it? Been trying it for quite long and i'm new to python.

Upvotes: 0

Views: 2633

Answers (1)

Leonardo Andrade
Leonardo Andrade

Reputation: 616

This occurs because the function glob.glob, returns an array of strings, and you are trying to pass this result to "datetime.fromtimestamp" function, that expects a number.

Any moment you "store" the modified date, to use after.

You needs to manipulate the files one by one. Example (I didn't test):

files = glob.glob(dataset_path+"/images/*.png")   
ts = files.sort(key=os.path.getmtime)
for file in ts:
    ms = os.path.getmtime(file)
    dt = datetime.fromtimestamp(ms)
...

or if you only needs the modification dates (without the path of file):

files = glob.glob(dataset_path+"/images/*.png")
ts = map(os.path.getmtime, files)
dts = map(datetime.fromtimestamp, ts)
...

References:

https://docs.python.org/2/library/datetime.html#datetime.date.fromtimestamp https://docs.python.org/2/library/glob.html#glob.glob

Upvotes: 2

Related Questions