How do you convert seconds (array) since specific time in Python? - python

I try to convert second data since 1993/01/01 like this
time = [7.57382412e+08, 7.57382436e+08, 7.57382461e+08, ...,
7.88918357e+08, 7.88918381e+08, 7.88918406e+08]
I can convert it one by one like this
datetime.datetime(1993,1,1) + datetime.timedelta(seconds=time[0])
If I enter the array into timedelta
datetime.datetime(1993,1,1) + datetime.timedelta(seconds=time)
It is showing a TypeError:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported type for timedelta seconds component: numpy.ndarray
How can I figure it out ?

Try using list comprehension as below:
[datetime.datetime(1993,1,1) + datetime.timedelta(seconds=each) for each in time]

Related

How do i convert a modified list of The Alphabet into a number?

i want to convert the sentence from variable (salam) into numbers. The conversion table is like a modified alphabet just like in (char2).
My expected output is a 3x3 matrix, inside is the converted number from(salam) using (char2)
salam = "APAKABARBROOOOO"
salam = salam.lower
output = []
char2 = [' ','a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z','.',',']
i = 0
while i <= 15:
np.array(char2.index(salam[i]))
i = i+1
and the output is
Traceback (most recent call last):
File "C:\Users\dragg\testing funtction losaot[sn[ga\main.py", line 12, in <module>
np.array(char2.index(salam[i]))
TypeError: 'builtin_function_or_method' object is not subscriptable
here is the image for clarity
The problem is from salam.lower. It should be salam.lower().
Without the () you are just referencing the .lower object.

int can't convert non-string with explicit base in for loop with fetchval

I am getting more and more confused in python.
when i try on one row, it works, but when i work on the whole rows of one column, it shows error.
i want to use the function convert_hex_to_int for each row in the column,
but it shows me the error
Traceback (most recent call last):
File
"C:/Users/ranic/.PyCharmCE2018.3/config/scratches/scratch_2.py", line
59, in
result_print = (convert_hex_to_int(hex_int, 4))
File "C:/Users/r/.PyCharmCE2018.3/config/scratches/scratch_2.py", line 32,
in conver
t_hex_to_int
splitted = [hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)] TypeError: 'str' object cannot be
interpreted as an integer
here is my code:
cnxn = pyodbc.connect(conn_str)
cnxn.add_output_converter(pyodbc.SQL_VARBINARY, hexToString)
cursor = cnxn.cursor()
def convert_hex_to_int(n:int, interval:int):
splitted = [hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)]
return [int(hex(unpack('<H', pack('>H', int(i, 16)))[0]), 16) for i in splitted]
try:
cursor.execute(query)
row=cursor.fetchval()
row_list=[]
while row is not None:
row=cursor.fetchval()
hex_int = int(row, 16)
result_print = (convert_hex_to_int(hex_int, 4))
result_float = [float("{0:.2f}".format((i) * 10 ** -2)) for i in result_print]
row_list.append(result_float)
print(row_list)
Please leave any comment if I miss something, thanks in advance.
When I debugged it, it shows something like this:
Debugged screen
*sorry I had to attach the image as it is the debugged screen and i cant copy the code, and it had to be in link because i am a new user
**edit: i think it has to do with the use of .fetchval twice, but im not too sure
If the line
[hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)]
Results in
TypeError: 'str' object cannot be interpreted as an integer
Then n must not be an integer.
Observe, if n is '0x94069206':
>>> hex('0x94069206')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
As the code is taking slices of n it looks as if n needs to be a string, so the line should be:
splitted = [n[2:][i:i + interval] for i in range(0, len(n[2:]), interval)]
It follows that the function signature should be
def convert_hex_to_int(n:str, interval:int)
On the other hand, if n is an int then the next line needs to be reworked.

TypeError: 'float' object cannot be interpreted as an integer ( python 3.4 version)

I am trying to run a video file and getting error as below.
$ /usr/bin/python3.4 /home/ramakrishna/PycharmProjects/Lanedect/driving-lane-departure-warning-master/main.py
Traceback (most recent call last):
File "/home/ramakrishna/PycharmProjects/Lanedect/driving-lane-departure-warning-master/main.py", line 19, in <module>
img_aug = process_frame(img)
File "/home/ramakrishna/PycharmProjects/Lanedect/driving-lane-departure-warning-master/lane.py", line 615, in process_frame
output = create_output_frame(offcenter, pts, img_undist_, fps, curvature, curve_direction, binary_sub)
File "/home/ramakrishna/PycharmProjects/Lanedect/driving-lane-departure-warning-master/lane.py", line 467, in create_output_frame
whole_frame = np.zeros((h*2.5,w*2.34, 3), dtype=np.uint8)
TypeError: 'float' object cannot be interpreted as an integer
Below line is reason for error.
np.zeros((h*2.5,w*2.34, 3), dtype=np.uint8)
np.zeros expects dimensions as integers, while h*2.5 and w*2.34 evaluates as float. If you wish you can cast arguments to integer using int().
I finally got the solution to it..I initially tried replacing floating values to 3 and 2 for 3.5 and 3.24 respectively.But got error as these values reduce the total frame dimension.Then changed it to
np.zeros((h*3,w*3,3), dtype=np.uint8) and it works..!!

TypeError: %d format: a number is required, not numpy.float64

Trying to plot, I got the following error from matplotlib:
TypeError: %d format: a number is required, not numpy.float64
This is the complete traceback (I've modified path names):
Traceback (most recent call last):
File ".../plotmod.py", line 154, in _plot
fig.autofmt_xdate()
File ".../local/lib/python2.7/site-packages/matplotlib/figure.py", line 426, in autofmt_xdate
for label in ax.get_xticklabels():
File ".../local/lib/python2.7/site-packages/matplotlib/axes.py", line 2620, in get_xticklabels
self.xaxis.get_ticklabels(minor=minor))
File ".../local/lib/python2.7/site-packages/matplotlib/axis.py", line 1118, in get_ticklabels
return self.get_majorticklabels()
File ".../local/lib/python2.7/site-packages/matplotlib/axis.py", line 1102, in get_majorticklabels
ticks = self.get_major_ticks()
File ".../local/lib/python2.7/site-packages/matplotlib/axis.py", line 1201, in get_major_ticks
numticks = len(self.get_major_locator()())
File ".../local/lib/python2.7/site-packages/matplotlib/dates.py", line 595, in __call__
'RRuleLocator estimated to generate %d ticks from %s to %s: exceeds Locator.MAXTICKS * 2 (%d) ' % (estimate, dmin, dmax, self.MAXTICKS * 2))
TypeError: %d format: a number is required, not numpy.float64
Where can this error come from?
Some basic research I've made results:
the error is not the real error, but instead one which is caused while trying to format the RuntimeError message that matplotlib.dates raises
the formatting error was due to python's %d, which, it seems, cannot handle numpy.float64 instances
the instance which has contained that data type is either estimate, which is some inner calculation result of matplotlib, or MAXTICKS, which is probably a constant, hence I tend to believe it's the first option
the calculation of estimate involves date2num which should return legitimate values, and _get_unit() and _get_interval(), which go deep enough into the module, and this is where my research stops.
I can easily reproduce the error in my entire software framework, but I can't isolate it for easy reproduction code. I think it tends to happen when the entire axis that should be plotted is very short (say, up to a few minutes long).
Any thoughts?
It seems you have a NaN or infinity that you are trying to format as an integer which raises the error (there's no such thing as a NaN or Inf for the int datatype).
In [1]: import numpy as np
In [2]: '%d' % np.float64(42)
Out[2]: '42'
In [3]: '%d' % np.float64('nan')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython console> in <module>()
TypeError: %d format: a number is required, not numpy.float64
In [4]: '%d' % np.float64('inf')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
ipython console> in <module>()
TypeError: %d format: a number is required, not numpy.float64
You could go into the matplotlib file (or use a python debugger) that generates the error and change the print line to have a %f which will work with all numpy floats. ('%f' % np.float64('nan') returns 'nan').
Convert numpy float to Python float manually.
np.asscalar(np.float64(42))

On Windows, how to convert a timestamps BEFORE 1970 into something manageable?

Summary: "negative" timestamps on Mac work fine, but on Windows I can't convert them into something usable.
Details:
I can have a file on Windows whose modification time is, say 1904:
$ ls -l peter.txt
-rw-r--r-- 1 sync Administ 1 Jan 1 1904 peter.txt
In python:
>>> import os
>>> ss = os.stat('peter.txt')
>>> ss.st_mtime
-2082816000.0
Great. But I can't figure out how to turn that negative timestamp into a date/time string. On Mac this code works fine.
>>> datetime.fromtimestamp(-2082816000)
datetime.datetime(1904, 1, 1, 0, 0)
And from here I can do whatever I want in terms of formatting.
But on Windows it fails:
>>> datetime.fromtimestamp(-2082816000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: timestamp out of range for platform localtime()/gmtime() function
And trying anything else I can think of fails:
>>> time.gmtime(-2082816000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: (22, 'Invalid argument')
the wonderful python-dateutil package doesn't seem to have this facility. I've looked though time, calendar, and datetime module. Any help?
>>> datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)
datetime.datetime(1904, 1, 1, 8, 0)
Using Ignacio's idea, this function will convert any timestamp to a proper naive datetime object:
def convert_timestamp_to_datetime(timestamp):
import datetime as dt
if timestamp >=0:
return dt.datetime.fromtimestamp(timestamp)
else:
return dt.datetime(1970, 1, 1) + dt.timedelta(seconds=int(timestamp))

Categories