How to insert todays date automatically? - python-3.x

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.

Related

Change panda date format into another date format?

How do I convert this format below into the result format ?
import pandas as pd
date = pd.date_range('2022-01-01',2022-01-31', freq = 'H')
Result:
'2021-01-01T01%3A00%3A00',
What is the correct name for the result time format ? Have tried using urlilib.parse module, but it did not have T and it can take 1 date.
Thank you !
This so called url encode , so we need urllib, notice here %3A = ':'
import urllib
date.astype(str).map(urllib.parse.quote)
Out[158]:
Index(['2022-01-01%2000%3A00%3A00', '2022-01-01%2001%3A00%3A00',
....

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

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