Clearing a line of output in Python - python-3.x

So, I'm super super new to Python and programming in general. I'm still learning the most basic of commands and terminology. My question is I'm trying to print the datetime in an infinite loop, but only on one line.
I would like the output in the shell to display the date and time and then clear the previously displayed datetime and replace it with the new value. I can't seem to figure out what I'm missing, and reading through different questions, I can't seem to find what I'm looking for. Any thoughts, help, or guidance would be appreciated. Trying to read the Python Documentation is not helping me at all at this point. This is what I've figured out so far:
import datetime
import time
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
time.sleep(30)
This Generates:
The Current date is 03/28/2017
The Current Time is 19:09
The Current date is 03/28/2017
The Current Time is 19:10
I'd like it to say:
The Current date is 03/28/2017
The Current Time is 19:09
Then, text above removed and replaced with
The Current date is 03/28/2017
The Current Time is 19:10
Datetime screenshot

One way is to use ANSI escape sequences:
import datetime
import time
import sys
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
sys.stdout.write("\033[F") # Cursor up one line
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(30)
Another option:
import datetime
import time
import os
while True:
today = datetime.date.today()
now = datetime.datetime.now()
print ("The Current date is ", (today.strftime('%m/%d/%Y')))
print ("The Current Time is ", (now.strftime('%H:%M')))
time.sleep(30)
os.system('clear')

Related

Time cannot be set in the past condition Python

What I need to do.
I need this program to not allow a user to input a date that's in the past. when I try it as it currently is i get the following error message. TypeError: '<' not supported between instances of 'datetime.datetime' and 'str'.
from datetime import datetime
from datetime import date
def addNewItems():
end = 4
while end == 4:
ToDoList = [ ]
Name = input("Enter the name of your task")
dateIn = input("Enter the task completion date. yyyy/mm/dd HH:MM:SS")
date = datetime.strptime(dateIn, "%Y/%m/%d %H:%M:%S")
now = datetime.now()
now_ = now.strftime("%d/%m/%Y %H:%M:%S")
if date < now_:
print("Time entered is in the past! Select options again")
continue
if Name in ToDoList:
print("Task already exists! Select options again")
continue
if date < now_ and Name not in ToDoList:
ToDoList.append(Name, date)
print("Task Added Sucessfully")
break
You actually need two datetime objects to use the < comparison directly.
You just need to compare date with now, intead of date with now_ in order to do what you want.
And just an advice. You're importing date from datetime library, so you should avoid creating variables with the same name if you intend calling the original date somewhere else in your code

Python3 deltatime as string for file search

I'm trying to search a file for yesterdays date, and save the line to another file. When I put the date in to search "8/25/2020" everything works fine. When I pull the current date, then subtract 1 day it doesn't work when adding it to line.startswith(). What am I doing wrong? Also I had to format the year as %y%y because the dates in the file are the full year not the last 2 digits. Thankfully its 2020.
from datetime import date, timedelta, datetime
yesterday = (datetime.now()-timedelta(days=1)).strftime("%m/%d/%y%y")
print(yesterday)
def check():
with open("1.txt", "r") as f, open("2.txt", "w") as e:
for line in f:
if line.startswith(yesterday):
e.write(line)
print(line)
check()
After attempting multiple ways to get the code to work I finally figured out the issue.
from datetime import date, timedelta, datetime
yesterday = (datetime.now()-timedelta(days=1)).strftime("%-m/%d/%Y" + ":")
print(yesterday)
def check_data():
with open("1.txt", "r") as f, open("2.txt", "w") as e:
for line in f:
if line.startswith(yesterday):
e.write(line)
print(line)
check_data()
I needed to remove the 0 padding in the date. %-m/%d/%Y -m in the date format fixed the issue.

How to insert todays date automatically?

I want to insert today's date in the following code automatically.
import shutil
shutil.copy(r"C:\Users\KUNDAN\Desktop\Backup\Cash MAR.2017 TO APR.2019.accdb",
r"F:\Cash MAR.2017 TO APR.2019 (11-09-19).accdb ")
print("DONE !!!")
First off, I'm not 100% sure of your question. If this doesn't answer it as you're expecting, please reformat your question to add clarity.
You can do this via the datetime library and string formatting. For example (using UK date format):
import shutil
from datetime import datetime as dt
today = dt.today().strftime('%d-%m-%y')
src = "C:/Users/KUNDAN/Desktop/Backup/Cash MAR.2017 TO APR.2019.accdb"
dst = "F:/Cash MAR.2017 TO APR.2019 ({today}).accdb".format(today=today)
shutil.copy(src, dst)
print("DONE !!!")
I have found these two links very useful:
string formatting
datetime formatting using strftime
import datetime
datetime_now = datetime.datetime.now()
print(datetime_now)
It will print the date and time for now and you can choose what format you like.

Delete some characters of last print / Update last print [Python 3.7.3]

Searched a lot about this but it is not working in Python 3.7.3 Shell.
There a lot of similar question (for example Remove and Replace Printed items which refers to an 8 years old Python version though), where they succesfully solve the problem using control characters \r and \b. But in my case I'm not able to solve the problem.
I would like to have an output like amount: x/y (where x current position and y the length of a string or a list) which is updated at each iteration, ie the part x/y has to be deleted and the part x+1/y has to be written, while keeping the string amount:.
What I tried so far
(1)
import sys
import time
word='simple'
for i in range(len(word)):
if i+1 < 10:
print('amount: '+'0'+str(i+1)+'/'+str(len(word)+1), end='\r')
else:
print('amount: '+str(i+1)+'/'+str(len(word)+1), end='\r')
time.sleep(0.5)
output
(2)
import sys
import time
word='simple'
for i in range(len(word)):
if i+1 < 10:
sys.stdout.write('amount: '+'0'+str(i+1)+'/'+str(len(word)))
else:
sys.stdout.write('amount: '+str(i+1)+'/'+str(len(word)))
sys.stdout.write("\b \b")
time.sleep(0.5)
output

Compare a user inputted value to an iterated value in a list

I am trying to compare values in a list of files (named as a date) to a user inputted start and end date, but I'm having some trouble when iterating the through the list in comparing the values.
Here is the code:
import os
import datetime
from tkinter.filedialog import askdirectory
x = askdirectory()
start = input('Enter start date (ddmmyyyy): ')
end = input('Enter end date (ddmmyyyy): ')
start = datetime.datetime.strptime(start, "%d%m%Y").strftime("%Y%m%d")
end = datetime.datetime.strptime(end, "%d%m%Y").strftime("%Y%m%d")
start = int(start)
end = int(end)
for files in os.walk(x):
file = files[2]
if '2' in file[1]:
file = [int(i) for i in file]
print(len(file))
for i in file:
if start >= file >= end:
fr.file_reader(time,rdata,intensity,files[i])
print(files[i])
When I run this, I get the following error:
TypeError: '>=' not supported between instances of 'int' and 'list'
I have tried converting the input to an integer, tried converting the list itself to integers but that didn't help. I know that at the moment it is reading the file as the whole list in the if loop, I just want it to read the ith file and iterate through, in order to read that file using my working file reader program. I can't work out how to achieve this.
Here is an what the first 10 files in my file list looks like. It's full length is 312 items so I won't copy it all here.
['20151123000103', '20151123220540', '20151124000043', '20151124003712', '20151125000055', '20151125070850', '20151126000101', '20151126000204', '20151126000330', '20151126000513']
If I could get any help with this I'd be most grateful :)
So I fixed it, the error itself was fixed by replacing "file" with "i". Knew it would be something small and simple.

Resources