Datetime Module, Time - python-3.x

I'm trying to print the actual time on an hourly based automated Email, but the program is repeating the first printed time again again. For Example, if the first rounds starts at 6:00 AM cst,again in the next email it is printing the same instead of 7:00, where I'm going wrong with the code below
import pytz
from datetime import datetime
import time
utc = timezone('UTC')
central = pytz.timezone('US/Central')
today = datetime.now(central)
crntDte = today.strftime("%m/%d/%Y")
crntTime = datetime.now(central).strftime('%H:%M')
def Action():
print('Process started at '+ crntDte + " " + crntTime)
schedule.every(2).minutes.do(Action)
while True:
schedule.run_pending()
time.sleep(1)
crntDte is working fine, but crnTime is printing the sametime everyhour

Well, your timezone looks not properly set. There are two timezone that are from pytz and datetime. I think you have to specify which one you will use.
import pytz
from datetime import datetime
import time
central = pytz.timezone('US/Central')
today = datetime.now(central)
crntDte = today.strftime("%m/%d/%Y")
crntTime = today.strftime('%H:%M')
print('Process started at '+ crntDte + " " + crntTime)
The result is then (for now)
Process started at 10/19/2019 09:18
When you do some schedule, then you have to re-calculate the time. So, your action should have all the definitions not only the print statement.
import pytz
from datetime import datetime
import time
def Action():
central = pytz.timezone('US/Central')
today = datetime.now(central)
crntDte = today.strftime("%m/%d/%Y")
crntTime = today.strftime('%H:%M')
print('Process started at '+ crntDte + " " + crntTime)
schedule.every(2).minutes.do(Action)
while True:
schedule.run_pending()
time.sleep(1)
There are not updated automatically.

Related

Passing run_date in seconds to apscheduler's add_job

I want to schedule a function in APScheduler to happen only once in the specified time from now. The run_date date trigger accepts datetime objects and/or strings there of:
from datetime import datetime
import os
from apscheduler.schedulers.asyncio import AsyncIOScheduler
try:
import asyncio
except ImportError:
import trollius as asyncio
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = AsyncIOScheduler()
scheduler.add_job(tick, 'date', run_date=datetime.fromordinal(datetime.toordinal(datetime.now())+1))
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
# Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
try:
asyncio.get_event_loop().run_forever()
except (KeyboardInterrupt, SystemExit):
pass
Is there a built-in functionality in APScheduler to specify the delay time directly in seconds, e.g.something like application_start_time + specified_delay? I tried datetime.fromordinal(datetime.toordinal(datetime.now())+1) as argument to run_date for 1 second after the starting point of my application, but this only hangs for ever without calling the tick function showing the following deprecation message:
Press Ctrl+C to exit
/tmp/a.py:30: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_forever()
What you probably wanted was:
from datetime import datetime, timedelta, timezone
scheduler.add_job(tick, "date", run_date=datetime.now(timezone.utc) + timedelta(seconds=1))

extract multiple URLs using the datetime function

In this program i am not using request or beautiful soup function. I'm instead only using the datetime to extract the URLs. Now in the current program, I have written to extract the values for a long period. I want to make it in such a way that, if I automate this program and it runs today, it will extract yesterday's data. Similarly if it runs tomorrow, it will extract todays data and so on.
here is the code,
import datetime
from datetime import date, datetime,timedelta
import warnings
import datetime
import pandas as pd
import wget
import glob
import os
warnings.filterwarnings("ignore")
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
from urllib.error import HTTPError
def date_range(start_date,end_date):
for n in range(int((end_date-start_date).days)):
yield start_date + timedelta(n)
def get_urls(base_url):
part_two = "/dailyCoal1-"
end_part = ".xlsx"
start_date = date(2020,11,1)
end_date = datetime.datetime.now().date()
start_urls = list()
for single_date in date_range(start_date, end_date):
start_urls.append(single_date.strftime(base_url+'%d-%m-%Y'+part_two+'%Y-%m-%d'+end_part))
return start_urls
def excel_download(link,out):
#downloads a given link provided to a output directory in out
wget.download(link,out)
if __name__ =="__main__":
base_url = "https://npp.gov.in/public-reports/cea/daily/fuel/"
mypath = "/Users/vp/Desktop/temp"
temp_folder = '/Users/vp/Desktop/temp'
out_folder = "/Users/vp/Desktop/NPP"
log_file = os.path.join(out_folder,'debug_log_npp.log')
out_file = os.path.join(out_folder,'Energy_inputs_npp.csv')
file_links = get_urls(base_url)
for link in file_links:
try:
excel_download(link,temp_folder)
except HTTPError:
content = "HTTP issue while capturing data for this link - " + link
log_writer(log_file,content)
continue
file = glob.glob(os.path.join(temp_folder,'*.xlsx'),recursive=True)[0]
df = pd.read_excel(file)
To capture yesterday's data, i created this in the main function where i check for yesterday = and then cancel if it isnt yesterday. But then its throwing error as it constantly picks the start date as its day one.
if(date_time_obj != Yesterday):
os.remove(file)
content = "Date mis-matched - " + str(date_time_obj) + " " + str(Yesterday)
In this program, date_time_obj - is the date it is currently trying to extract data for.
Everyday if this program runs at 8pm, it needs to only capture one day before data on a daily basis.
if this cannot be done in datetime, but only on request or bs4, then how do i approach this problem?
I don't know if you wanted a valid link as your code doesn't seem to produce those for me but you only need to tweak to work off start_date only and return a single item to return yesterday's link matching with your current output for same date.
import datetime
from datetime import date, datetime,timedelta
import warnings
import datetime
import pandas as pd
import glob
import os
warnings.filterwarnings("ignore")
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
from urllib.error import HTTPError
def get_url(base_url):
part_two = "/dailyCoal1-"
end_part = ".xlsx"
start_date = datetime.datetime.now().date() + timedelta(-1)
start_url = start_date.strftime(base_url+'%d-%m-%Y'+part_two+'%Y-%m-%d'+end_part)
return start_url
def excel_download(link,out):
#downloads a given link provided to a output directory in out
wget.download(link,out)
if __name__ =="__main__":
base_url = "https://npp.gov.in/public-reports/cea/daily/fuel/"
mypath = "/Users/vp/Desktop/temp"
temp_folder = '/Users/vp/Desktop/temp'
out_folder = "/Users/vp/Desktop/NPP"
log_file = os.path.join(out_folder,'debug_log_npp.log')
out_file = os.path.join(out_folder,'Energy_inputs_npp.csv')
file_link = get_url(base_url)
print(file_link)

The python program with datetime mofule

I write this code in python in order to read the minute of windows clock and recognize weather it is even or odd and do it 10 times with random sleep time between 5 to 10 seconds:
from datetime import datetime
import random
import time
wait_time = random.randint(5,11)
time.sleep(wait_time)
for i in range(10):
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
But when I run it, sleep time works ok but it show the answer just one time. I think I should write the lines in other arrangement. But I don't know how to fix it.
You need to rearrange your lines according to your own description as below. Same lines but another ordering.
from datetime import datetime
import random
import time
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
for i in range(10):
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
wait_time = random.randint(5,11)
time.sleep(wait_time)

AttributeError: 'str' object has no attribute sleep

I get the error in the title of this question. How can I fix that? The posts I found on Google did it like I did but it does not work for me.
Thank you for your help!
#!/usr/bin/python3
import os
import json
import datetime
import cgi
import time
def save(number_input, current_time):
i = 0
while os.path.exists("datei/datei{}.txt".format(i)):
i += 1
datei = {
"input": number_input,
"zeit": current_time
}
with open("datei/datei{}.txt".format(i), "w+") as file:
json.dump(datei, file)
form = cgi.FieldStorage(encoding="utf-8")
number = form.getvalue("first")
time = datetime.datetime.today().strftime("%d.%m.%Y %H:%M:%S")
save(number, time)
print("<p>Sie haben {} in einer .txt Datei gespeichert! </p>".format(number))
time.sleep(4)
print("Location: main.py")
print()
In this line:
time = datetime.datetime.today().strftime("%d.%m.%Y %H:%M:%S")
You are overwritting the time variable, that contained a module and making it a string.
This is an example of working code
#!/usr/bin/python3
import os
import json
import datetime
import cgi
import time
def save(number_input, current_time):
i = 0
while os.path.exists("datei/datei{}.txt".format(i)):
i += 1
datei = {
"input": number_input,
"zeit": current_time
}
with open("datei/datei{}.txt".format(i), "w+") as file:
json.dump(datei, file)
form = cgi.FieldStorage(encoding="utf-8")
number = form.getvalue("first")
time_str = datetime.datetime.today().strftime("%d.%m.%Y %H:%M:%S")
save(number, time)
print("<p>Sie haben {} in einer .txt Datei gespeichert! </p>".format(number))
time.sleep(4)
print("Location: main.py")
print()
Notice I've changed time to time_str, this way your time variable is untouched and you can call sleep :)

Only write when serial device outputs data

I am trying to make a data-logger than writes the output from a serial device that only outputs once per minute. I need it to have a time stamp on the output. The code I have so far will log the output but it keeps logging blanks with a timestamp in-between the device's output. How do I get it to only write a line with the timestamp when the device has output?
#!/usr/bin/env python
Log data from serial port
import argparse
import serial
import datetime
import time
import os
timestr = time.strftime("%Y%m%d")
Tstamp = time.strftime("%Y/%m/%d %H:%M ")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
outputFile.write(Tstamp + " " + data + '\n')
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")
Sorry for the poor formatting I am not sure how to make it look right on here.
By adding if x!= "" and indenting properly I got it to work. Now I just need ot fix it to append the file and not overwrite it.
#!/usr/bin/env python
# Log data from serial port
import argparse
import serial
import datetime
import time
import os
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
if data !="":
outputFile.write(time.strftime("%Y/%m/%d %H:%M ") + " " + data )
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")

Resources