Pandas/Python, Pickup latest file in directory - python

Is it possible to pickup the latest file in my folder?
I currently type in the month to pickup the file of choice, However I am not sure how to pickup the latest modified file?
I am confused trying to use max since the date I Input I use is used twice and want to use it to pickup latest smalldate and then pickup the file in that folder.
( {smalldate} for parent folder and {monthyear} for a part of the file name)
monthyear = input("Enter Full Month and Year: ") #Ie August 2021
smalldate = pd.to_datetime(monthyear, format="%B %Y").strftime("%b %Y")
userid = str(os.getlogin())
gco = (rf"C:\Users\{userid}\OneDrive\Report\{smalldate}\Detail Report - {monthyear}.xlsx")

Related

Issue with calculating password age date in Python

I'm rebuilding my PowerShell script with Python.
Sole purpose of that is to easily insert data to Postgre DB tables with Python.
PowerShell script works as it should, but when it comes to Python I encountered a obstacle.
In this loop, I gather all data - most like direct reports from specific AD account. As you may see, I already gather account name, name/surname, e-mail address and password last set date.
The problem is to calculate password age. In PS it was pretty easy, but when I ran a code in Python, I get an Exception has occurred: TypeError can't subtract offset-naive and offset-aware datetimes
Here is the part of the code:
reports = getDirectReports(managers_name)
for users in reports:
for user in users.directReports.values:
if 'cn=ext.' in user.lower():
user_details = getUserDetails(user)
print(user_details[0].cn.value)
print(user_details[0].givenName.value)
print(user_details[0].sn.value)
print(user_details[0].pwdLastSet.value)
print(user_details[0].mail.value)
current_date = datetime.now()
start_date = user_details[0].pwdLastSet.value
if (start_date == 0):
password_age = 'NULL'
else:
password_age = current_date - start_date ```

Getting the name of a folder using Exchangelib

I have looked at:
How to get the parent folder name of Message with Exchangelib python
But have been unable to make this work using the following debugging code:
for item in docdead.all().order_by('-datetime_received')[:3000]: #look into the inbox the first 3K emails order desc by date received
if item.datetime_received < ews_bfr: #if the mail if older than the custom date in the EWS format then apply rule
print (item.subject)
print (item.datetime_received)
print (item.sender.email_address)
print (item.sender.name)
print (item.body)
print(SingleFolderQuerySet(
account=account,
folder=account.root
).get(id=item.parent_folder_id.id))
for attachment in item.attachments:
print (attachment.name)
I get:
ValueError: EWS does not support filtering on field 'id'
I am sure its a simple error, but I would appreciate any help.
If you're just querying one folder, then parent_folder_id will always point to that folder.
If you're querying multiple folders at a time, here's the general way to look up a folder name by ID:
from exchangelib.folders import FolderId, SingleFolderQuerySet
folder_name = SingleFolderQuerySet(
account=account,
folder=FolderId(id=item.parent_folder_id.id),
).resolve().name

How do I use python to create outlook events in multiple calendars

This is the code I've been using. It works when I want to create an appointment, but only in my main calendar. Do any of you know how to create the appointments in a secondary calendar?
import win32com.client
from win32com.client import Dispatch
outlook = win32com.client.Dispatch("Outlook.Application")
def sendMeeting():
appt = outlook.CreateItem(1) # AppointmentItem
appt.Start = "2021-5-28 16:10" # yyyy-MM-dd hh:mm
appt.Subject = "Fake meeting"
appt.Duration = 30 # In minutes (60 Minutes)
appt.Location = "The bat cave"
appt.Save()
appt.Send()
Do you mean a secondary Exchange account in the profile? Or a delegate Exchange mailbox?
In the former case, open the store from the Namespace.Stores collection, open the Calendar folder using Store.GetDefaulFolder(olFolderCalendar), create new item using MAPIFolder.Items.Add. In the latter case, you can use Namespace.GetSharedDefaultFolder(Recipient, olFolderCalendar) (where Recipient can be retrieved from Namespace.CreateRecipient).
If it is a subfolder in your primary store, you can access it from its parent folder and call MAPIFolder.Items.Add. E.g. if it is a subfolder of your default Calendar folder, use outlook.Session.GetDefaultFolder(olFolderCalendar).Folders.Item("The name"). If it is on the same level as your Calendar folder, use outlook.Session.GetDefaultFolder(olFolderCalendar).Parent.Folders.Item("The name").

With Pelican, how to set or access variables between Python code and themes?

I need to pass down the original source file name (*.md file) into the sidebar.html. How can I do that?
From this site (http://pelican.readthedocs.org/en/3.6.3/themes.html), I understand some variables are available, and all capital letter variables in pelicanconf.py files are also available, but I don't know how to get the information such as the original source file in the theme files.
I think there might be a simpler way, but using jinja filter works fine for me ( http://linkpeek.com/blog/how-to-add-a-custom-jinja-filter-to-pelican.html)
Steps to take:
Pre-setup
I make the name of the original markup file to be in the format YEAR-MONTH-DAY-NAME to be recovered from the url of the page.
Create a filter
The filter is given the url, and from the url, I can recover the original source md file path.
def tosource(url):
# example input
# posts/2014/01/26/python-unittest-structure/index.html
# posts/2014/01/26/ocaml-vs-java/index.html
# posts/2014/01/25/why-ocaml-comparison-with-python/index.html
if url.startswith("posts"):
(posts, year, month, day, name) = url.split('/')[:-1]
res = "%s/%s/%s-%s-%s-%s.md" % (year, month, year, month, day, name)
else:
res = "/" # implement later
return res
Update pelicanconf.py
Teach pelican the name and location of the filter.
import sys
sys.path.append('.')
import sourcename
JINJA_FILTERS = {'sourcename':sourcename.tosource}
OPENCONTENT = "open:///pelican/knowledge_blog/content"
As is written in http://docs.getpelican.com/en/3.5.0/themes.html#theming-pelican, all capital letter variables in the conf file are accessible in the theme files.
Update sidebar.html
I added one line of code in sidebar.html to use the Jinja filter for getting the original md file path.
Click to Edit
Generate the html
Run make html and test.

Python FTP Most Recent File [duplicate]

This question already has answers here:
Python FTP get the most recent file by date
(5 answers)
Closed 4 years ago.
How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space.
from ftplib import FTP
ftp = FTP('ftp.cwi.nl')
ftp.login()
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print line
output:
drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .
dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..
-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX
Just to make some corrections:
date_str = ' '.join(line.split()[5:8])
time.strptime(date_str, '%b %d %H:%M') # import time
And to find the most recent file
for line in data:
col_list = line.split()
date_str = ' '.join(line.split()[5:8])
if datePattern.search(col_list[8]):
file_dict[time.strptime(date_str, '%b %d %H:%M')] = col_list[8]
date_list = list([key for key, value in file_dict.items()])
s = file_dict[max(date_list)]
print s
If the FTP server supports the MLSD command (and quite possibly it does), you can use the FTPDirectory class from that answer in a related question.
Create an ftplib.FTP instance (eg aftp) and an FTPDirectory instance (eg aftpdir), connect to the server, .cwd to the directory you want, and read the files using aftpdir.getdata(aftp). After that, you get name of the freshest file as:
import operator
max(aftpdir, key=operator.attrgetter('mtime')).name
To parse the date, you can use (from version 2.5 onwards):
datetime.datetime.strptime('Mar 21 14:32', '%b %d %H:%M')
You can split each line and get the date:
date_str = ' '.join(line.split(' ')[5:8])
Then parse the date (check out egenix mxDateTime package, specifically the DateTimeFromString function) to get comparable objects.

Categories

Resources