Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Comparing dates
#1
Hello, I am not sure that this is being placed into the right area of the forum so for that if I am wrong sorry. For starters Im new to getting into python and still learning as I am very very green and new. Im have a code that I wrote where Im quering a mysql data base looking at latest backups that occur the day before. I have this data being printer to the body of the email, along with a text file. What I'm trying to research and learn is how that I can do something along the line where since the back up occurs the day before is use date time to compare the output date to yesterday's date and make sure they match.

here is an example of the email that I send out via python. As you can see the email was sent today, the subject line contains the date for yesterday as I checking the backup that occurs anywhere between 10-11 pm est the day before. The body of the email has the output of the query result with the data and time stamp

From: Polimeni, Timothy <Timothy_Polimeni@xxxxxxx>
Sent: Friday, May 1, 2020 6:00 AM

Subject: PNC Checker Results for 2020-04-30

Beltway, 2020-04-30 23:18:14
Keystone, 2020-04-30 23:49:18
Freedom, 2020-04-30 23:00:14
New England, 2020-04-30 23:50:23



What I would like to do is something like this, if date = yesterday's date for each line print in the subject line successful, if the date in the body of the query does not equal the previous date then print failed in the subject line. Below is the full code which I wrote to complete the task this far. Any help on how to go about this or doing it would be appreciated.

#! /usr/bin/python3.6
import pymysql
import datetime
date = str(datetime.date.today()-datetime.timedelta(1))
from pncnetworkdata import *
from datetime import datetime
import logging
import smtplib
from email.message import EmailMessage
from emaillist import *

logger = logging.getLogger('pncnetwork')
hdlr = logging.FileHandler('/opt/scripts/errors/pncnetworkerrors.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.WARNING)
#logging.info('Started')



try:
    markets = ["Beltway", "Keystone", "Freedom", "New England"]
    count = 0
    cursorRowCount = 0
    recordPrint = ""
    for HOST in HOSTS:
        db_con = pymysql.connect(host=HOST, port=3306, user=USERNAME, passwd=PASSWORD, db=DATABASE) 
                                                                                                      

        sql_select_Query = "SELECT * FROM pncnetwork where id=(SELECT MAX(id) FROM pncnetwork)"
        cursor = db_con.cursor()
        cursor.execute(sql_select_Query)
        records = cursor.fetchall()
        for row in records:
            recordPrint += markets[count] + ', ' + str(row[2]) + "\n" 
        cursorRowCount += cursor.rowcount
        count += 1
        db_con.close()
#    print ("Total number of rows in pncnetwork is: ", cursorRowCount)
    print ("\nPrinting each pncnetwork record\n", recordPrint)



# This section will print the script to file in /opt/scripts/output


    path = "/opt/scripts/output/PNCChecker.txt"
    print("PATH", path);

    with open(path, "w+") as f:
    # Write Data to file
     f.write (recordPrint)
     f.close()
# This Section will attach above file to an email and send it
     msg = EmailMessage()
     msg["From"] = FROM
     msg["Subject"] = f"PNC Checker Results for {date}"
     msg["To"] = TO
     msg.set_content(recordPrint)
     msg.add_attachment(open( "/opt/scripts/output/PNCChecker.txt").read(), filename= "PNCChecker.txt")
     
     s = smtplib.SMTP('mailrelay.zxc.com')
     s.send_message(msg)

#This section prints successful email sent and any errors

    print ("Successfully sent email")
except SMTPException:
    print("Error: unable to send email")

except Exception as e:
    print("ERROR ", str(e))
    logger.error('message')
    raise
Reply
#2
see: https://pymotw.com/3/datetime/#date-arithmetic for example
Reply
#3
(May-01-2020, 05:37 PM)Larz60+ Wrote: see: https://pymotw.com/3/datetime/#date-arithmetic for example

Thank you however I’m not sure these examples help much. I know how to use for the most part date time. Where I’m stuck and can’t figure out is how with the output from MySQL to perform a if else is what I’m thinking I need to do against the function recordPrint which is printing out example Beltway followed by the date from the last backup.

I want to make an if else to where if the date printed equals time.date with a delta of 1 then print successful, if the output doesn’t equal the previous day of when the script was ran it prints failed. This the part where I am struggling.

Can you provide any suggestions or examples how something like this maybe performed? All prior help with your additional logging and more has always pointed me in the right direction to resolve my issues this on just has me fully stumped.

Thanks in advance
Reply
#4
When you shall compare dates you need eg string str(row[2] to be a datetime object.
Here i quick demo,and i use Pendulum because it's great and build on top of datetime,just doing stuff better.
>>> import pendulum
>>> 
>>> s = 'Beltway, 2020-04-30 23:18:14'
>>> my_date = s.split(', ')[1]
>>> my_date
'2020-04-30 23:18:14'
>>> type(my_date)
<class 'str'>

# Can parse a string automatically   
>>> my_date = pendulum.parse(my_date)
>>> my_date
DateTime(2020, 4, 30, 23, 18, 14, tzinfo=Timezone('UTC'))
>>> type(my_date)
<class 'pendulum.datetime.DateTime'>

# Now that is a datetime object can compare,eg just use yesterday as a example
>>> yesterday = pendulum.yesterday()
>>> yesterday
DateTime(2020, 5, 2, 0, 0, 0, tzinfo=Timezone('Europe/Berlin'))
>>> 
>>> my_date < yesterday
True
>>> my_date == yesterday
False
>>> my_date <= yesterday
True
>>> my_date >= yesterday
False
Reply
#5
(May-03-2020, 01:24 AM)snippsat Wrote: When you shall compare dates you need eg string str(row[2] to be a datetime object.
Here i quick demo,and i use Pendulum because it's great and build on top of datetime,just doing stuff better.
>>> import pendulum
>>> 
>>> s = 'Beltway, 2020-04-30 23:18:14'
>>> my_date = s.split(', ')[1]
>>> my_date
'2020-04-30 23:18:14'
>>> type(my_date)
<class 'str'>

# Can parse a string automatically   
>>> my_date = pendulum.parse(my_date)
>>> my_date
DateTime(2020, 4, 30, 23, 18, 14, tzinfo=Timezone('UTC'))
>>> type(my_date)
<class 'pendulum.datetime.DateTime'>

# Now that is a datetime object can compare,eg just use yesterday as a example
>>> yesterday = pendulum.yesterday()
>>> yesterday
DateTime(2020, 5, 2, 0, 0, 0, tzinfo=Timezone('Europe/Berlin'))
>>> 
>>> my_date < yesterday
True
>>> my_date == yesterday
False
>>> my_date <= yesterday
True
>>> my_date >= yesterday
False

Thank you so I see what can be say a hard code date, will I need to manually update or change this daily or is it possible to say like today minus 1 to equal the output or am I looking/thinking and making this way more complicated? Sorry this is all new to me and first time comparing a date that’s in the past hope what I’m trying to do makes sense
Reply
#6
(May-03-2020, 01:32 AM)tpolim008 Wrote: it possible to say like today minus 1 to equal the output or am I looking/thinking and making this way more complicated?
Yes no problem look at documentation it's really good.
>>> import pendulum
>>> 
>>> today = pendulum.today()
>>> today 
DateTime(2020, 5, 3, 0, 0, 0, tzinfo=Timezone('Europe/Berlin'))
>>> 
>>> today.subtract(days=1)
DateTime(2020, 5, 2, 0, 0, 0, tzinfo=Timezone('Europe/Berlin'))
>>> print(today.subtract(days=1))
2020-05-02T00:00:00+02:00
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020