I have a table in x.db
file which has two columns. One column is of type datetime
and the other is of type millisecond
. I need to read both columns as one in python.
sample datetime and millisecond attached here
I want to read the datetime
(this will be my x
value for the plot) as
2022-05-25 14:20:26.948
2022-05-25 14:20:26.968
2022-05-25 14:20:26.988
2022-05-25 14:20:27.008
2022-05-25 14:20:26.028
2022-05-25 14:20:26.048
so I can plot the desired data in millisecond.
The code that I am trying to build is here
conn = sqlite3.connect('./x.db')
cur = conn.cursor()
cur.execute('select * from data ')
tmp_row = cur.fetchall()
#print(tmp_row)
conn.close()
xdate=[]
abc=[]
dfg=[]
for row in tmp_row:
tmp=row[0]
yy=tmp[0]+tmp[1]+tmp[2]+tmp[3]
mm=tmp[5]+tmp[6]
dd=tmp[8]+tmp[9]
HH=tmp[11]+tmp[12]
MM=tmp[14]+tmp[15]
ss=tmp[17]+tmp[18]
tmp2=row[1]
print(tmp2)
t=tmp2[0]+tmp2[1]+tmp2[2]
tmpdt=dd+"/"+mm+"/"+yy+" "+HH+":"+MM+":"+ss+"."+t
#print(tmpdt)
#print(tmpdt)
The error I am getting is
t=tmp2[0]+tmp21+tmp2[2] TypeError: 'int' object is not subscriptable
Another problem is that some have single digit value. I need to add 00
in front while concating
timestamp_S t_ms
2022-05-25 14:20:27 8
required is
2022-05-25 14:20:27.008
You can use datetime.datetime.strptime
and datetime.datetime.replace
functions to get what you wanted.
from datetime import datetime
for row in tmp_row:
t = datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S") # t = datetime(2022, 5, 25, 14, 20, 26)
t = t.replace(microsecond = int(row[1]) * 1000) # t = datetime(2022, 5, 25, 14, 20, 26, 948000)
print(str(t)[:23])) # str(t) = "2022-05-25 14:20:26.948000", str(t)[:23] = "2022-05-25 14:20.26.948"