Python Forum
Store Previous date to calculate delta from today
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Store Previous date to calculate delta from today
#1
Hi! New to the coding world and developing my first script. I want the script to store a date of last login (previouslogin) and then compare it with today's date (currentlogin) to calculate a delta of days and then perform the action of deleting a folder if the delta is greater than a certain value and if its not then simply store 'currentlogin' date as 'previouslogin' date so that the script can rerun on the next login. Important point is that, 'currentlogin' date has to become 'previouslogin' date for the next instance of running the script. Here is what I have written.

import datetime
import shutil
import arrow #an alternative library for handling dates and times

# Step 1: Read the previous login date
print(previouslogin(currentlogin))

# Step 2: Check current login date
today = datetime.date.today()
currentlogin = today.strftime("%Y-%m-%d")
print(currentlogin)

    #calculating date delta using Arrow and somehow the delta function in datetime was not working
a = arrow.get(previouslogin)
b = arrow.get(currentlogin)
delta = b-a
print (int(delta.days))

# Step 4: If part OR 'decision part'
if delta.days > 1:
    shutil.rmtree("folder2bdel")
    print("Folder removed!")
else:
#Step 5: Mark 'currentlogin' as 'previouslogin'
    def previouslogin(currentlogin):
        return(previouslogin(currentlogin))
print ("The job is done!")
#Step 6: Exit the program  (Yet to be written)


And here is what I am getting:

Output:
Traceback (most recent call last): File ".\defautodel.pyw", line 6, in <module> print(previouslogin(currentlogin)) NameError: name 'previouslogin' is not defined
I am very new and learning it on my own so I may not be able to understand too much technicality at this point of time. Any help to make the script work as intended would be appreciated.
Reply
#2
First off, you have to define the function before the line that you use it on. The next thing I see is that your defining a function inside an else statement. All your functions should be defined on the first column. You're also executing the function within itself, making a recursive function, but since there is nothing to stop it from executing itself it will keep going until you hit the recursive limit and get an error. I also don't get what that function is supposed to do. Can't say much more till the code gets fixed up.
Reply
#3
(May-05-2020, 09:44 PM)SheeppOSU Wrote: First off, you have to define the function before the line that you use it on.

This is the tricky part which I am not able to grasp. I understand that you are saying what I am doing in #Step 5 needs to be done before #Step 1, only then I will be able to call that function in #Step 1. But where my thought process is stuck, is that how to tell the program in its own language, that what is 'today / currentlogin' will be 'yesterday/previouslogin' tomorrow. Can you please help me sort that part out please. And this needs to repeat. i.e. every time the script is run, it shall take the 'currentlogin' of previous session as 'previouslogin'. How can I tell the program this, while I haven't given it any value for the current login?

(May-05-2020, 09:44 PM)SheeppOSU Wrote: The next thing I see is that your defining a function inside an else statement. All your functions should be defined on the first column. You're also executing the function within itself, making a recursive function, but since there is nothing to stop it from executing itself it will keep going until you hit the recursive limit and get an error.

Thanks for these tips. I will try to fix these.

(May-05-2020, 09:44 PM)SheeppOSU Wrote: I also don't get what that function is supposed to do. Can't say much more till the code gets fixed up.

The script is supposed to delete a defined folder if the computer is being loggedin after a certain number of days. If the computer is loggedin within the specified number of days. The folder shall not be deleted, only the currentlogin date shall appear as the previouslogin date upon the next login.
Reply
#4
(May-05-2020, 11:08 PM)Captain_Wolf Wrote: How can I tell the program this, while I haven't given it any value for the current login?
You'd use two variables if you just want to keep track of those two. If you want to keep track of more, say the last 100, then use a list. I'll give some examples.
Two variables -
previousLogin = ""
currentLogin = ""

#Do the calculations
if #not logged in within time:
    #Delete Folder
else:
    previousLogin = currentLogin
Using a list
previousLoginList = []
currentLogin = ""
maxLoginArchive = 100 #Max number of passwords that can be saved in the list. Note: You can go much much higher than 100 of you want.

#Do the calculations

if #not logged in within time:
    #Delete Folder
else:
    previousLoginList.append(currentLogin)
    while len(previousLoginList) > maxLoginArchive: #Will remove the first element from the list until the length is back down to the max. The first element will always be the oldest one recorded. The newest one is in the back of the list.
        previousLoginList.pop(0)
I don't know how you plan to make currentLogin, so this is how you'd make the current one the previous one. Also, if you decide to use a function, they're usually used to separate logic, out of one big chunk of code, if you're repeatedly using a decent sized chunk of code, or simply to organize things.
Hope this answers all your questions.
Reply
#5
Thanks for your detailed response. I tried to use your list method in the below code:

import datetime
import shutil

# PREVIOUS PART
previousloginlist = ['2020-05-07 14:14:51']
#Step 1: Define the variables
def previouslogin(previousloginlist):
    return (previousloginlist[0]) #the index value '0' from the previousloginlist

format = format = "%Y-%m-%d %H:%M:%S"
previouslogindate = datetime.datetime.strptime(previousloginlist[0],format)

print(previouslogindate)

# CURRENT PART
currentlogindate = datetime.datetime.now()
print(currentlogindate)

delta = previouslogindate - currentlogindate
print(delta.days)

#If condition is yet to be inserted here

previousloginlist.pop()
print(previousloginlist)
previousloginlist.append(currentlogindate)
print(previouslogindate)
I get the following results:

Output:
2020-05-07 14:14:51 2020-05-08 01:46:54.755361 -1 [] 2020-05-07 14:14:51
This shows that the 'previousloginlist' value at Line 5 has become hard coded and is not being replaced by the 'currentlogindate' value. However if I delete this hard coded value (to leave the list empty) I get the following output.

Output:
Traceback (most recent call last): File ".\definingprevlogin.pyw", line 11, in <module> previouslogindate = datetime.datetime.strptime(previousloginlist[0],format) IndexError: list index out of range
How to fix this mess? :)
Reply
#6
I was running tests with it and I don't really see the problem. The first time you run it, you can grab the latest time, as that will be the first login. I also don't really know how you plan on running this program. You may need to use a txt file in which to save the list if the program is not always running, other than that I only did one small change to your code. I changed line 11 to the following.
previouslogindate = datetime.datetime.strptime(previousloginlist[len(previousloginlist)-1], Format)
Then if you did plan on saving the code would look something like that (I used l for short)
l = []
l = loadData()
if not l:
    l = [datetime.datetime.now()]

#code

saveData(l)
If you have any other problems I'm happy to help
Reply
#7
Thanks for your response.

(May-07-2020, 10:59 PM)SheeppOSU Wrote: You may need to use a txt file in which to save the list if the program is not always running

Before writing this script I have actually used this method and it worked perfectly fine for me, except for one glitch. i.e. I was not able to bundle that text file with the script file to give to someone else or make it work on another computer. So I decided to include this information in one script file only and get rid-off the text file.

(May-07-2020, 10:59 PM)SheeppOSU Wrote: If you have any other problems I'm happy to help

I ran the script with the changes advised by you but now I ran into some other errors. It shouldn't be this difficult, its just that I am not literate enough in this field at this point of time. I guess I need to make do with the previous .txt file version as it was simple and it worked.

Thanks again for all your help.
Reply
#8
(May-08-2020, 06:04 PM)Captain_Wolf Wrote: I was not able to bundle that text file with the script file to give to someone else
Whenever you have multiple files that you need to bundle together, put it in a folder all together, and then you can "zip" the folder to create a zip file which contains all the files. This can then be given to someone as one single file. Also, you'd need to make the .py file a .exe file so that anyone can run it, because in order to run a .py file you need a Python compiler that handles everything, however with exe files, any computer can run it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 266 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Python date format changes to date & time 1418 4 634 Jan-20-2024, 04:45 AM
Last Post: 1418
  i tried to install python for the first time today and pretty certain im being remote brianlj 2 564 Oct-03-2023, 11:15 AM
Last Post: snippsat
  Calculate next rows based on previous values of array divon 0 1,801 Nov-23-2021, 04:44 AM
Last Post: divon
  Date format and past date check function Turtle 5 4,310 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  Datetime strp\delta problems korenron 2 2,087 Jun-13-2021, 10:35 AM
Last Post: korenron
  Need to identify only files created today. tester_V 5 4,683 Feb-18-2021, 06:32 AM
Last Post: tester_V
  How to add previous date infront of every unique customer id's invoice date ur_enegmatic 1 2,248 Feb-06-2021, 10:48 PM
Last Post: eddywinch82
  Make list of dates between today back to n days Mekala 3 2,408 Oct-03-2020, 01:01 PM
Last Post: ibreeden
  How to add date and years(integer) to get a date NG0824 4 2,905 Sep-03-2020, 02:25 PM
Last Post: NG0824

Forum Jump:

User Panel Messages

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