Python reading date from excel throws error - python

I am trying to read date from excel file using xlrd module. Below is my code for this :
# Variables
myfile = '/home/mobaxterm/.git/Operation_Documentation/docs/Servicing Portal User & Certificate Inventory.xlsx'
mydate = 'Expiration Date'
row_head = 0
# Import required modules
import xlrd
import datetime
today = datetime.date.today()
book = xlrd.open_workbook(myfile)
sheet = book.sheet_by_index(1)
for col_index in range(sheet.ncols):
print xlrd.cellname(row_head,col_index),"-",
print sheet.cell(row_head,col_index).value
if sheet.cell(row_head,col_index).value == mydate:
for raw_index in range(sheet.nrows):
expire = sheet.cell(raw_index,col_index).value
print expire
expire_date = datetime.datetime(*xlrd.xldate_as_tuple(expire, book.datemode))
print 'datetime: %s' % expire_date
break
While running the code i am getting following error :
Traceback (most recent call last):
File "cert_monitor.py", line 31, in <module>
expire_date = datetime.datetime(*xlrd.xldate_as_tuple(expire, book.datemode))
File "/usr/lib/python2.6/site-packages/xlrd/xldate.py", line 61, in xldate_as_tuple
xldays = int(xldate)
ValueError: invalid literal for int() with base 10: 'Expiration Date'
Can anyone suggest what could be the issue here?
Thanks for your time.

I believe that you should only skip the header:
for raw_index in range(1, sheet.nrows):
...
You are checking that sheet.cell(row_head,col_index).value == mydate, and then you want to iterate over the rows, but you should skip row_head first - it is ==mydate, which is not a date but a simple 'Expiration Date' string.

Related

pywintypes.com_error. in Outlook. I am creating an outlook appointment, it errors on assigning time. Says that the object doesn't support method

I have this code:
import win32com.client
import pythoncom
import datetime
def saveMeeting(start, end, subject, location, attachments, recipients):
outlook = win32com.client.Dispatch("Outlook.Application", pythoncom.CoInitialize())
ns = outlook.GetNamespace("MAPI")
session = ns.Session
## Find the accounts that are of exchange type
acc = []
for account in session.Accounts:
if account.AccountType == 0: #0 - outlookExchange, 1 - outlookIMAP, 2 - outlookPop3
#print(account)
acc.append(account)
appointment = outlook.CreateItem(1) #1 - AppointmentItem
# Fill in the data needed
appointment.SendUsingAccount = acc
appointment.Start = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
appointment.StartTimeZone = outlook.TimeZones("Central Standard Time")
appointment.End = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
appointment.EndTimeZone = outlook.TimeZones("Central Standard Time")
appointment.Subject = f"HOLDER-{subject}"
appointment.Location = location
appointment.MeetingStatus = 1
if attachments != '':
appointment.Attachments.Add(attachments)
recipients = filter(None, recipients)
for recipient in recipients:
r = appointment.Recipients.Add(recipient)
r.Resolve()
appointment.Save()
# Only use .Display() if using tkinter
appointment.Display()
saveMeeting("2022-03-02 14:00:00", "2022-03-02 14:30:00", "Subject of the Meeting","Location", "", ["altisjessienino18#gmail.com", "ajn_dulay#smcm.edu.ph"])
But, it just gives me this error.
Traceback (most recent call last):
File "C:\Users\user\Desktop\Project\createInvite.py", line 100, in <module>
saveMeeting("2022-03-02 14:00:00", "2022-03-02 14:30:00", "Subject of the Meeting","Location", "", ["user1#gmail.com", "user2#smcm.edu.ph"])
File "C:\Users\user\Desktop\Project\createInvite.py", line 42, in saveMeeting
appointment.End = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\dynamic.py", line 686, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The object does not support this method.', None, 0, -2147352567), None)
I am trying to create an Appointment using pywin32 and python. But the problem is that sometimes it works, and sometimes it does not like this code here, it seems like there is a problem that I could not see or hidden somewhere. The main issue here is that I am trying to fix the date problem (it turns to UTC+6 instead of UTC-6).
It seems you didn't format the date correctly. Try to use the following format:
"mm/dd/yyyy hh:mm AMPM"
Also it make sense to set the time zone first (before start and end of the meeting).

BeautifulSoup4 and Requests Module 'IndexError: list index out of range'

I'm new to web scraping with python and am having a problem with the weather web scraping script I wrote. Here is the whole code 'weather.py':
#! python3
import bs4, requests
weatherSite = requests.get('https://weather.com/en-CA/weather/today/l/eef019cb4dca2160f08eb9714e30f28e05e624bbae351ccb6a855dbc7f14f017')
weatherSoup = bs4.BeautifulSoup(weatherSite.text, 'html.parser')
weatherLoc = weatherSoup.select('.CurrentConditions--location--kyTeL')
weatherTime = weatherSoup.select('.CurrentConditions--timestamp--23dfw')
weatherTemp = weatherSoup.select('.CurrentConditions--tempValue--3a50n')
weatherCondition = weatherSoup.select('.CurrentConditions--phraseValue--2Z18W')
weatherDet = weatherSoup.select('.CurrentConditions--precipValue--3nxCj > span:nth-child(1)')
location = weatherLoc[0].text
time = weatherTime[0].text
temp = weatherTemp[0].text
condition = weatherCondition[0].text
det = weatherDet[0].text
print(location)
print(time)
print(temp + 'C')
print(condition)
print(det)
It basically parses the weather information from 'The Weather Channel' and prints it out. This code was working fine yesterday when I wrote it. But, I tried today and it is giving me the following error:
Traceback (most recent call last):
File "C:\Users\username\filesAndStuff\weather.py", line 16, in <module>
location = weatherLoc[0].text
IndexError: list index out of range
Replace:
weatherLoc = weatherSoup.select('.CurrentConditions--location--kyTeL')
# print(weatherLoc)
# []
By:
weatherLoc = weatherSoup.select('h1[class*="CurrentConditions--location--"]')
# print(weatherLoc)
# [<h1 class="CurrentConditions--location--2_osB">Hamilton, Ontario Weather</h1>]
As you can see, your suffix kYTeL is not the same for me 2_osB. You need a partial match on class attribute (class*=) (note the *)

Value Error: Microsecond must be in 0..999999

Hi i am using the library win32com.client to read emails from an outlook sharedmailbox and i get a value error:Microsecond must be in 0..999999. I tried formatting the "ReceivedDate" as "%Y-%D-%M %H:%M:%S" with no luck. do you know what else i can try?
Question 2: im trying to count how many emails have not been replied to but i dont see a property for that in the documentation. SO i went with reading all that have a "FlagRequest" marked as completed. I would have the representatives go with this process as a way to tell if the emails have been complete.
import win32com.client
def readEmail():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item('SharedMailbox, TEST')
inbox = folder.Folders.Item('Inbox')
messages = inbox.Items
counter = 0
for message in messages:
rcvd_dt = message.ReceivedTime
if message.FlagRequest != 'Follow up' and str(rcvd_dt) >= '2020-06-01 00:00:00':
counter +=1
print(counter)
print(received_dt)
traceback:
Traceback (most recent call last):
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 422, in <module>
main()
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 409, in main
readEmail()
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 89, in readEmail
rcvd_dt = message.ReceivedTime
File "C:\Program Files (x86)\Python37-32\lib\site-
packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
ValueError: microsecond must be in 0..999999
What i tried:
rcvd_dt= datetime.strptime(str(rcvd_dt.split('.')[0], '%Y-%m-%d %H:%M:%S')
but get error:
valueerror: time data '2' does not match format %Y-%m-%d %H:%M:%S.%f'
if i try:
rcvd_dt= datetime.strptime(str(rcvd_dt.split('.')[0], '%Y-%m-%d %H:%M:%S.%f')
i get :
valueerror: time data '2020-06-16 08:53:56' does not match format %Y-%m-%d.%f'

Python - error when executing script

I am trying to execute this script:
import time
from SECEdgar.crawler import SecCrawler
def get_filings():
t1 = time.time()
# create object
seccrawler = SecCrawler()
companyCode = 'AAPL' # company code for apple
cik = '0000320193' # cik code for apple
date = '20010101' # date from which filings should be downloaded
count = '10' # no of filings
seccrawler.filing_10Q(str(companyCode), str(cik), str(date), str(count))
seccrawler.filing_10K(str(companyCode), str(cik), str(date), str(count))
seccrawler.filing_8K(str(companyCode), str(cik), str(date), str(count))
seccrawler.filing_13F(str(companyCode), str(cik), str(date), str(count))
t2 = time.time()
print "Total Time taken: ",
print (t2-t1)
if __name__ == '__main__':
get_filings()
I am putting this code in a file filings.py , then attempt to run it from terminal (Mac user)
python filings.py
But I am getting the following error:
Traceback (most recent call last):
File "filings.py", line 2, in <module>
from SECEdgar.crawler import SecCrawler
File "build/bdist.macosx-10.10-intel/egg/SECEdgar/crawler.py", line 6, in <module>
File "build/bdist.macosx-10.10-intel/egg/SECEdgar/config.py", line 22, in <module>
File "/Library/Python/2.7/site-packages/configparser.py", line 995, in __getitem__
raise KeyError(key)
KeyError: 'Paths'
What am I doing wrong?
Looks like there's an error in the package you installed.
Try uninstalling and reinstalling.
pip uninstall SECEdgar
pip install SECEdgar
I found the solution, it was basically a quite silly thing:
date = '20010101' # date from which filings should be downloaded
should be
date = '20010101' # date UNTIL which filings should be downloaded
so if you put the starting date you would end up with download 0 files, but if you put the end date then you would download them all successfully, seems to be working OK now :)

Convert string to datetime to epoch

I am using Python to query a MySQL table and getting one datetime in string format, which is stored in row[3]. I need to convert this string timestamp to epoch seconds.
import MySQLdb
import os
import datetime
try:
db = MySQLdb.connect("localhost","root","","test" )
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
cursor = db.cursor()
cursor.execute ("SELECT * from main_tbl WHERE login_user_name='kumar'")
data = cursor.fetchall()
for row in data :
print row[3] ###printing 2014-09-26 12:24:23
date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
print date
On execution it throws this error:
2014-09-26 12:24:23
Traceback (most recent call last):
File "test1.py", line 22, in <module>
date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
TypeError: must be string, not datetime.datetime
What am I doing wrong?
I have also tried the following:
epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));
But I get this error:
Traceback (most recent call last):
File "test1.py", line 29, in <module>
epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));
File "C:\Python27\lib\_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "C:\Python27\lib\_strptime.py", line 322, in _strptime
found = format_regex.match(data_string)
TypeError: expected string or buffer
The value in row[3] is already in the datetime.datetime format as it is being clearly pointed out by the traceback. So there is no need for creating the variable date. You can use the row[3] directly as a datetime.datetime object.
Just try printing:
print type(row[3])
That should give the type as datetime.datetime
row[3] is already in datetime.datetime format.
From your question its sounds like you want convert to EPOCH
so do something like:
import time
epochTime = time.mktime(row[3].timetuple())
print epochTime
Then check if the converted epoch is correct or not:
print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epochTime))
print row[3]
Verify last two statements have the same output.

Categories

Resources