Python3 deltatime as string for file search - python-3.x

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.

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

How to strip a string from a datetime stamp?

I am reading the attached excel file (only an image attached) using Pandas. There is one row with DateTime stamp with following format (M- 05.02.2018 13:41:51). I would like to separate/remove the 'M-' from DateTime in the whole row.
import pandas as pd
df=pd.read_excel('test.xlsx')
df=df.drop([0,1,2,3])
I would then like to use the following code to convert to Datetime:
df.iloc[0]= pd.to_datetime(df.iloc[0], format='%d.%m.%Y %H:%M:%S')
Can please someone help me to remove the 'M-' from the complete row?
Thank you.
Excel-file (image)
Use pandas.Series.str.strip to remove 'M-' from the rows:
If removing from the rows:
df['Column_Name'] = df['Column_Name'].str.strip('M- ')
If removing from columns or DataFrame headers:
df.columns = df.columns.str.strip('M- ')
You may want Series.str.lstrip to remove leading characters from row.
df.iloc[0] = df.iloc[0].str.lstrip('M- ')

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.

deleting the 7 days older files in a folder using the timestamp in the file name in python

i have the daily uploading of my files which are in the formate allproduct_bbc_20190409.csv,allproduct_bbc_20190112.csv,allproduct_bbc_20190514.csv the number of the files is getting bigger and i wanted to delete the files which are older than 7 days using the timestamp in the filename..how can i solve this??
path = "C:\\Users\\User\\Desktop\\test"
days_to_subtract = 7
d = dt.today().strftime('%Y%m%d') - timedelta(days=7).strftime('%Y%m%d')
print (d)
lines = []
for filename in os.listdir(path):
date_filename = dt.strptime(filename.split(" ")[0].filename.split('_')[2],**strong text**'%Y%m%d')
if date_filename < dt.dt.now()-dt.timedelta(days=days_to_subtract):
with open(os.path.join(path, filename), 'r') as f:
lines.extend(f.readlines())
i expect the output to be like as below in the folder by deleting all the files which are older than 7 days
allproduct_bbc_20190514.csv
Code provided below can be used to delete files from a directory by checking the date in filename.
The first method(get_date_from_filename) returns a date object from the filename passed to it, if the filename is in proper format.
The second method(should_delete) takes to arguments -> file_date and days.
If the file_date is older than days from today then it will return True otherwise False.
The third method delete_old_files deletes the files while making use of the first two methods to perform checks. It takes two arguments path and days. Path should be a path to a directory inside which the method will check all files and delete them if they are days or more older than today. I have passed a default for both these arguments according to your question, but you can change the default according to your need or pass something else in the last line where this method is called.
from datetime import date, timedelta
import os
def get_date_from_filename(filename):
"""Retrieve a date object from filename of format xyz_yyyymmdd.xyz."""
date_string = filename
# Get rid of file extension
try:
date_string = filename.split('.')[-2]
except IndexError:
raise ValueError('Oops, looks like an invalid filename!')
# Take out date part from filename
date_string = date_string[-8:]
if len(date_string) != 8:
raise ValueError('Oops, looks like an invalid filename!')
# Get year as integer
try:
year = int(date_string[:4])
except ValueError:
raise ValueError('Invalid year in filename!')
# Get month as integer
try:
month = int(date_string[4:6])
except ValueError:
raise ValueError('Invalid month in filename!')
# Get date as integer
try:
day = int(date_string[6:])
except ValueError:
raise ValueError('Invalid date in filename!')
# Convert to date object and return it
return date(year, month, day)
def should_delete(file_date, days):
"""Check if the given file_date is given days or more older than today."""
today = date.today()
return file_date < today - timedelta(days=days)
def delete_old_files(path, days=7):
"""Delete old files in a given directory."""
if not os.path.isdir(path):
raise NotADirectoryError('Given path is not a directory!')
for filename in os.listdir(path):
try:
delete_file = should_delete(get_date_from_filename(filename), days)
except ValueError:
print(f'Skipping {filename}')
continue
if delete_file:
print(f'Deleting {filename}')
try:
os.remove(os.path.join(path, filename))
except:
print(f'Unexpetced error while deleting {filename}!')
else:
print(f'Skipping {filename}')
# pass days too if required
delete_old_files(path="C:\\Users\\User\\Desktop\\test")
delete_old_files(path="C:\\Users\\User\\Desktop\\another_folder")
delete_old_files(path="D:\\Yet\\Another\\Folder")

Clearing a line of output in Python

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')

Resources