Auto refreshing mate-panel applet - python

Ubuntu restricts what you can do with timezones - most applications have a hard dependency on /etc/localtime, including the Clock applet in mate-panel. I am trying to write a python applet that shows the time in a timezone of the user's choice, but I can't get it to auto refresh - I'd like to display the current time every 1s.
#!/usr/bin/env python
from datetime import datetime
from time import gmtime, strftime, sleep
import pytz
from os.path import expanduser
from os.path import exists
import gi
TIMEZONE = 'Australia/Sydney'
DATE_FMT = '%Y-%m-%d %H:%M:%S'
gi.require_version("Gtk", "2.0")
gi.require_version("MatePanelApplet", "4.0")
from gi.repository import GObject, Gtk, MatePanelApplet
# I moved this code out of applet_fill() and into its own function
# so that I can call it with Gtk.timeout_add or GObject.timeout_add
# ...but I get the dreaded white dot when reloading the app.
def calc_datetime(applet, timezone):
dt_xxx = pytz.timezone(strftime("%Z", gmtime())).localize(datetime.now()).astimezone(pytz.timezone(timezone)).strftime(DATE_FMT)
DateLabel = Gtk.Label(timezone + ':- ' + dt_xxx)
applet.add(DateLabel)
applet.show_all()
# DateLabel.set_text() works, but not when looped.
#while True:
# DateLabel.set_text('Hello')
# sleep(1)
return DateLabel
def applet_fill(applet):
# define custom timezone in ~/.config/company/timezone
cfg_file = expanduser('~') + '/.config/company/timezone'
if exists(cfg_file):
with open(expanduser('~') + '/.config/company/timezone', 'r') as file:
timezone = file.read().replace('\n', '')
else:
timezone = TIMEZONE
DateLabel = calc_datetime(applet, timezone)
# I atempted different things here, but again, white dot in the panel.
#i = 1
#while True:
# sleep(1)
# DateLabel.set_text('test again')
# #i = i + 1
# GObject.idle_add(calc_datetime, applet, timezone)
#Gtk.timeout_add('100', calc_datetime, applet, timezone)
#DateLabel.set_text('test')
#return True
# this is called by mate-panel on applet creation
def applet_factory(applet, iid, data):
if iid != "MyClockApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("MyClockAppletFactory", True, MatePanelApplet.Applet.__gtype__, applet_factory, None)
I put notes in the code comments.

The problem is in calc_datetime
Functions you add with idle_add return True or False, which determines whether this function should be called again.
This idle_added function is called in mainloop. There you can update all the labels.

Related

if statement doesn't work in while loop with time lib python

Here is the code (only this):
import pytz
from time import sleep
from datetime import datetime
dt_format = "%H:%M"
tz = pytz.timezone('Asia/Riyadh')
jt = datetime.now(tz)
time_now = (jt.strftime(dt_format))
time = time_now.replace(":","")
timed1 = (int("1530")) #the time in 24h format
while True:
#print('azan on')
if timed1 == time_now:
print(time_now)
print(timed1)
print ("its the time")
sleep (90)
I tried to keep the format normal (15:30) but still the same.
(replace) not required you can delete if so.
You just have to update the time and put it in the loop and it will work , thanks to #MatsLindh (check comments)

'NoneType' 'NoneType' object is not iterable

I am trying to loop through a list of symbols to get rates for various currencies via the mt5. I use the code below but i get TypeError
d[i] = [y.close for y in rates1]
TypeError: 'NoneType' object is not iterable
I can't see where im going wrong i would like to use this structure to loop through create multiple dataframe and then make a big multiindex of all pairs and time using same kind of loop. I've not been coding long.
sym = ['GBPUSD','USDJPY','USDCHF','AUDUSD','GBPJPY']
# Copying data to dataframe
d = pd.DataFrame()
for i in sym:
rates1 = mt5.copy_rates_from(i, mt5.TIMEFRAME_M1, 5)
d[i] = [y.close for y in rates1]
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 18:38:11 2020
#author: DanPc
"""
# -*- coding: utf-8 -*-
"""
"""
import pytz
import pandas as pd
import MetaTrader5 as mt5
import time
from datetime import datetime
from threading import Timer
import talib
import numpy as np
import matplotlib as plt
from multiprocessing import Process
import sys
server_name = "" ENTER DETAILS HERE
server_num =
password = ""
#------------------------------------------------------------------------------
def actualtime():
# datetime object containing current date and time
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
#print("date and time =", dt_string)
return str(dt_string)
#------------------------------------------------------------------------------
def sync_60sec(op):
info_time_new = datetime.strptime(str(actualtime()), '%d/%m/%Y %H:%M:%S')
waiting_time = 60 - info_time_new.second
t = Timer(waiting_time, op)
t.start()
print(actualtime)
#------------------------------------------------------------------------------
def program(symbol):
if not mt5.initialize(login=server_num, server=server_name, password=password):
print("initialize() failed, error code =",mt5.last_error())
quit()
timezone = pytz.timezone("Etc/UTC")
utc_from = datetime.now()
######### Change here the timeframe 525600
# Create currency watchlist for which correlation matrix is to be plotted
sym = ['GBPUSD','USDJPY','USDCHF','AUDUSD','GBPJPY']
# Copying data to dataframe
d = pd.DataFrame()
for i in sym:
rates1 = mt5.copy_rates_from(i, mt5.TIMEFRAME_M1, 5)
d[i] = [y.close for y in rates1]
print(rates1)
mt5.shutdown()
if not mt5.initialize():
print("initialize() failed, error code =",mt5.last_error())
quit()
# starting mt5
if not mt5.initialize(login=server_num, server=server_name, password=password):
print("initialize() failed, error code =",mt5.last_error())
quit()
#------------------------------------------------------------------------------
# S T A R T I N G M T 5
#------------------------------------------------------------------------------
authorized=mt5.login(server_num, password=password)
if authorized:
account_info=mt5.account_info()
if account_info!=None:
account_info_dict = mt5.account_info()._asdict()
df=pd.DataFrame(list(account_info_dict.items()),columns=['property','value'])
print("account_info() as dataframe:")
print(df)
else:
print(mt5.last_error)
mt5.shutdown()
#------------------------------------------------------------------------------
def trading_bot():
symbol_1 = 'EURUSD'
symbol_2 = 'EURCAD'
while True:
program(symbol_1)
program(symbol_2)
time.sleep(59.8) # it depends on your computer and ping
sync_60sec(trading_bot)
copy_rates_from returns None if there is an error. The documentation suggests calling last_error() to find out what that error is.
(And no, I don't know why copy_rates_from doesn't just raise an exception to indicate the error. Apparently, the module is a thin wrapper around a C library.)
I came to this solution that creates a dictionary of dataframes.
sym = ["GBPUSD","USDJPY","USDCHF","AUDUSD","GBPJPY"]
# Copying data to dataframe
utc_from = datetime.now()
for i in sym:
rates = {i:pd.DataFrame(mt5.copy_rates_from(i, mt5.TIMEFRAME_M1, utc_from , 60),
columns=['time', 'open', 'low', 'high', 'close', 'tick_volume', 'spread', 'real_volume']) for i in sym}

How to run my computer's time setter as a silent backgound PID?

I guess my computer's battery of bios got dead; consequently the system time is never accurate, it is sometimes stuck at 1 PM with a faulty date, so I came up with this code with the idea of fetching universal time from an api and setting my computer's time accordingly.
My problem is how to make my code run in the background without printing any ping results to the screen or showing anything. I need it to function as a PID and keep alive as long as the computer is on.
PS: I am using Windows 7
from json import loads
from urllib.request import urlopen
import logging
from win32api import SetSystemTime
from datetime import datetime
from time import sleep
import re
from os import system
while True:
# connection is dead with 1, connection is alive with 0
connection_is_dead = 1
while connection_is_dead != 0:
connection_is_dead = system('ping -n 1 google.com')
logging.basicConfig(level=logging.INFO)
logging.disable(level=logging.INFO) # logging off
logging.info('Connection is up...')
try:
with urlopen("http://worldtimeapi.org/api/timezone/africa/tunis") as time_url:
text = time_url.read()
logging.info('Time api imported...')
mytime_dict = loads(text)
time_now = mytime_dict['datetime']
logging.info(time_now)
time_stamp = re.compile(r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+)[+|-].*')
time_match = list(map(int, re.match(time_stamp, time_now).groups()))
# winapi32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
dayOfWeek = datetime(*time_match[:3]).weekday()
SetSystemTime( *time_match[:2],dayOfWeek, *time_match[2:6], 0)
logging.info('Time updated successfully...')
#system('exit')
sleep(1800) # 3O min / reset time every 30 min
except:
logging.error('Time was not updated due to an unexpected error... ')
#system('exit')

How to parse datetime between logs?

I need to build a program that parse the logs and gives a date
The log only has hours, no dates, So what am I supposed to do?
I tried using datetime but it just enters the today date
import math
import os
import random
import re
import sys
import logging
import datetime
def main():
file = open("Desktop/a1.log", "r")
lines = file.readlines()
file.close()
today = datetime.date.today()
for line in lines:
print (today, line)
main()
The logs are like this:
10:47:01> Screen 1: 2560x1080 at (0,1080) work area 2327x1080 at (233,1080)
10:47:01> Screen 2: 2560x1080 at (0,0) work area 2304x1080 at (256,0) primary
10:47:01> Screen 3: 1440x2560 at (-1440,0) work area 1440x2560 at (-1440,0)
and I need to set a first date and last date. How can I do this?
When you use today = datetime.date.today() it is only grabbing the current time.
Instead you should use today = datetime.datetime.now()
Then you can use today.year, today.month, today.day, today.hour, today.minute, today.second to get the individual fields you want or today.strftime("%Y-%m-%d %H:%M") to get several values at once.
def main():
file = open("Desktop/a1.log", "r")
lines = file.readlines()
file.close()
today = datetime.datetime.now()
for line in lines:
print (today.strftime("%Y-%m-%d %H:%M"), line)
More details can be found here: https://docs.python.org/3.0/library/datetime.html

python3 - how to change date filter in pivot table?

I'm trying to make a script which will change every day date in pivot table to yesterday.
Unfortunately, every time when I try this code, Excel automatically calculates date and so from 2014-05-08 makes 41766. How to avoid this issue?
When I write it to 'normal' cell it works fine. Problem is only with pivot tables...
import win32com.client as win32
import datetime
import time
from datetime import date, timedelta
now = datetime.datetime.now()
yesterday = date.today() - timedelta(1)
wczoraj = yesterday.strftime("%Y-%m-07")
#----------------------------------------------------------------------
def excel():
""""""
xl = win32.gencache.EnsureDispatch('Excel.Application')
ss = xl.Workbooks.Open(r'D:\python\skrypty\test.xlsx')
sh = ss.Worksheets("Arkusz5")
xl.Visible = True
time.sleep(1)
#kolumn,
sh.Cells(2,2).Value = wczoraj
ss.Close(True)
xl.Application.Quit()
if __name__ == "__main__":
excel()
try changing "07" to "%d" in strftime

Categories

Resources