User Input function, if/else if parameter not followed - python

I have the following code that requires the user to input a date in format 2021/12/31. It then calculates the difference between date entered and today.
date = input('Enter your date: ')
delta = datetime.strptime(date, '%Y/%m/%d') - datetime.now()
print("difference is {} days".format(delta.days))
I would like for a 0 to be displayed if the wrong date format is entered but can't quite figure it out, I assume I need if / else like my attempt below but it's not quite working as it returns 0 no matter what.
date = input('Enter your date: ')
if date == '%Y/%m/%d':
delta = datetime.strptime(date, '%Y/%m/%d') - datetime.now()
print("difference is {} days".format(delta.days))
else:
print('0')

You can use the datetime to check if the format is right like:
try:
....datetime.datetime.strptime("99/99/99","%m/%d/%y")
except ValueError as err:
....print(err)

You can check the date format like this:
from datetime import datetime
date = str(input('Enter your date: '))
print(date)
format = "%Y-%m-%d"
try:
delta = datetime.now() - datetime.strptime(date, format)
print("difference is {} days".format(delta.days))
except ValueError as err:
print(err)

Related

how to pass date parameter in a rest request query in python: sysparm_query

what is the best way to filter a rest request by date?
would work passing a variable maybe like this:
today = date.today() today_90 = today - timedelta(days = 90)
service-now.com/api/now/table/incident?sysparm_limit=1000&sysparm_query=sys_created_on**dates values here?**
I try to understanding your problem:
from datetime import date, timedelta
import requests
today = date.today()
today_90 = today - timedelta(days = 90)
r = requests.get('https://xxxx.service-now.com/api/now/table/incident?sysparm_limit=1000&sysparm_query=sys_created_on>' + str(today_90) + '&sysparm_query=sys_created_on<' + str(today))

How to cut time in datetime.date?

I have 2 variables: datetime.date and datetime.datetime
import sqlite3
from datetime import date
#bot.message_handler(commands=['check'])
def start_message(message):
cursor = conn.execute("SELECT * from DATA WHERE id = ? ORDER BY DATE ", (message.from_user.id,))
row = cursor.fetchone() #datetime.datetime
datee = date.today() #datetime.date
print(datee - parse(row[2]).date())
bot.send_message(message.chat.id, row[1])
bot.send_message(message.chat.id, str(datee - parse(row[2])))
print is displaying -1 day, 0:00:00, but I need to take out the timestamp. How can I do it?
If you only want to print the days (without the hours,minutes,seconds), you can use the attribute.days, e.g.:
print((datee - parse(row[2]).date()).days)
this works because what you receive is not a date object anymore but a datetime.timedelta object.

Python Generating Date Time as Sting with time increments to generate URL

To Repeatedly call a web URL which has time stamp in the end,
Example URL
'https://mywebApi/StartTime=2019-05-01%2000:00:00&&endTime=2019-05-01%2003:59:59'
StartTime=2019-05-01%2000:00:00
is URL representation of Time 2019-05-01 00:00:00
endTime=2019-05-01%2003:59:59
is URL representation of Time 2019-05-01 00:00:00
Requirement is to make repetitive calls , with 4 hour window.
While adding 4 hours, the date may change,
Is there a lean way to generate the URL String,
Some thing like
baseUrl = 'https://mywebApi/StartTime='
startTime = DateTime(2018-05-03 00:01:00)
terminationTime = DateTime(2019-05-03 00:05:00)
while (startTime < terminationTime):
endTime = startTime + hours(4)
url = baseUrl+str(startTime)+"endtime="+str(startTime)
# request get url
startTime = startTime + hours(1)
You can use Datetime.timedelta as well as the strftime function as follows:
from datetime import datetime, timedelta
baseUrl = 'https://mywebApi/StartTime='
startTime = datetime(year=2018, month=5, day=3, hour=0, minute=1, second=0)
terminationTime = datetime(year=2018, month=5, day=3, hour=3, minute=59, second=59)
while (startTime < terminationTime):
endTime = startTime + timedelta(hours=4)
url = baseUrl + startTime.strftime("%Y-%m-%d%20%H:%M:%S") + "endtime=" + endtime.strftime("%Y-%m-%d%20%H:%M:%S")
# request get url
startTime = endTime
The following link is useful https://www.guru99.com/date-time-and-datetime-classes-in-python.html or you can look at the official datetime documentation.
edit: using what u/John Gordan said to declare the initial dates

Passing today's date for a date picker field in Selenium using Python

I am trying enter today's date into a date picker field rather than just click the today button and below is how my code is set up, but not able to do so. I am using BDD framework.
And I input todays date
#When('I input todays date')
def step_impl(context):
value_paystub_dateOfPayStub(context.webdriver)
Getting element of said date picker:
def get_dateOfPaystub(driver):
element = None
try:
element = WebDriverWait(driver, 70).until(
EC.visibility_of_element_located(
(By.XPATH, "//input[#id='chl.CustomerFinancials.primaryFinancialsForm.paystub.6134.DateOfPaystub']"))
)
except TimeoutException:
logger.error("Date of Paystub element was not found")
return element
Trying to enter today's date:
def value_paystub_dateOfPayStub(driver):
currentdate = datetime.datetime.today()
try:
element = get_dateOfPaystub(driver)
element.send_keys() # to set focus on the selector
element.send_keys(currentdate, "%m-%d-%Y")
except Exception:
logger.error("Unable to enter value into Paystub Employer Name field")
Any help would be appreciated.
You need to use strftime to format your date.
import datetime from datetime
element.send_keys(datetime.strftime(currentdate, '%m-%d-%Y'))
Here we need to define the locator for the calendar field to accept data dynamically as below.
calendar = "//p[contains(.,'{}')]"
and then use the below code to fetch today's date and select the appropriate date
import datetime
current_day = datetime.datetime.now().day
driver.find_element_by_xpath(calendar.format(current_day).click
Here is something I tried using css_selector:
import datetime
# Getting today's date
now = datetime.datetime.now()
tday = now.strftime("%m-%d-%Y")
# Selecting everything and clearing by backspace
elem.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE)
elem = driver.find_element_by_css_selector('#ID')
or
elem = driver.find_element_by_id('ID')
# Sending today's date
elem.send_keys(tday)
time.sleep(1)

How can I extract hours and minutes from a datetime.datetime object?

I am required to extract the time of the day from the datetime.datetime object returned by the created_at attribute, but how can I do that?
This is my code for getting the datetime.datetime object.
from datetime import *
import tweepy
consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
tweets = tweepy.Cursor(api.home_timeline).items(limit = 2)
t1 = datetime.strptime('Wed Jun 01 12:53:42 +0000 2011', '%a %b %d %H:%M:%S +0000 %Y')
for tweet in tweets:
print (tweet.created_at - t1)
t1 = tweet.created_at
I need to only extract the hour and minutes from t1.
I don't know how you want to format it, but you can do:
print("Created at %s:%s" % (t1.hour, t1.minute))
for example.
If the time is 11:03, then afrendeiro's answer will print 11:3.
You could zero-pad the minutes:
"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)
Or go another way and use tdate.time() and only take the hour/minute part:
str(tdate.time())[0:5]
import datetime
YEAR = datetime.date.today().year # the current year
MONTH = datetime.date.today().month # the current month
DATE = datetime.date.today().day # the current day
HOUR = datetime.datetime.now().hour # the current hour
MINUTE = datetime.datetime.now().minute # the current minute
SECONDS = datetime.datetime.now().second #the current second
print(YEAR, MONTH, DATE, HOUR, MINUTE, SECONDS)
2021 3 11 19 20 57
It's easier to use the timestamp for these things since Tweepy gets both:
import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))
datetime has fields hour and minute. So to get the hours and minutes, you would use t1.hour and t1.minute.
However, when you subtract two datetimes, the result is a timedelta, which only has the days and seconds fields. So you'll need to divide and multiply as necessary to get the numbers you need.

Categories

Resources