Using if condition in datetime format - python-3.x

I was given a question to get two time input from user as a function(opening_time,closing_time) and I had to determine the difference between the time,but if one of these values are not in time format,the returned value should be -1.I have computed the time difference but,I am unable to fix a condition that if any one of the variable is not in time format,return -1.
Please I am new to coding,so apologize for any mistake and be kind to write simple solution,not so complex one.
from datetime import datetime
def compute_opening_duration(opening_time, closing_time):
str_format = "%H:%M:%S"
if opening_time or closing_time != datetime.time.str_format:
print(-1)
else:
tdelta = datetime.strptime(closing_time,str_format)
- datetime.strptime(opening_time,str_format)
print(tdelta)

Try this - it will try to cast the inputs to a datetime using your provided string format. If it fails on either one, it will print -1.
from datetime import datetime
def compute_opening_duration(opening_time, closing_time):
str_format = "%H:%M:%S"
try:
t_open_time = datetime.strptime(closing_time,str_format)
t_closing_time = datetime.strptime(opening_time,str_format)
tdelta = datetime.strptime(closing_time,str_format) - datetime.strptime(opening_time,str_format)
print(tdelta)
except:
print(-1)
compute_opening_duration("04:10:21", "08:22:12")

Related

How to get rid of value 'None' after printing a fucntion with the Try and Except block

I've written a function like the following, it's pretty self-explaining and i can't properly summarize my task. So, the problem here is that my Try and Except block keep producing value 'None', which really screw me up in my next task when i tried to put it in an array and covnert it into a numpy array. Data_dict is a dictionary contains every attribute (as keys) of a data file i'm working on in this task.
TLDR: how can i stop the try and except block from producing value "None" or is there another way to execute my task.
I'm just 4 weeks into python and have no previous coding experience. Also, i'm using Jupyter Notebook. I've tried to add another Else block to get rid of the value but it just became worse.
import datetime
def compute_opening_duration(opening_time, closing_time):
#Input: two string: opening_time and closing_time
#Output: the opening duration in hours
#Return -1 if any time is in incorrect form.
str_format = "%H:%M:%S"
try:
a = datetime.datetime.strptime(closing_time, str_format) - datetime.datetime.strptime(opening_time, str_format)
print(a.total_seconds()/3600)
except ValueError:
print(-1)
print(compute_opening_duration('5:30:00', '16:00:00'))
#my 2nd task is to compile all the values of that function above and then put it an array
#then convert that into a numpy array and print out first 10 entries
a = list(compute_opening_duration(data_dict['Open'][i], data_dict['Close'][i]) for i in range (len(data_dict['Open'])))
a_numpyarray = np.asarray(a)
print(a_numpyarray[0:11])
i expected it to be numbers
but the actual output is: [None None None None None None None None None None None]
import datetime
import numpy as np
def compute_opening_duration(opening_time, closing_time):
#Input: two string: opening_time and closing_time
#Output: the opening duration in hours
#Return -1 if any time is in incorrect form.
str_format = "%H:%M:%S"
try:
a = datetime.datetime.strptime(closing_time, str_format) - datetime.datetime.strptime(opening_time, str_format)
return a.total_seconds()/3600
except ValueError:
return -1
# print(compute_opening_duration('5:30:00', '16:00:00'))
#my 2nd task is to compile all the values of that function above and then put it an array
#then convert that into a numpy array and print out first 10 entries
data_dict={
"Open" :['5:30:00'],
"Close": ['16:00:00']
}
a = list(compute_opening_duration(data_dict['Open'][i], data_dict['Close'][i]) for i in range (len(data_dict['Open'])))
a_numpyarray = np.asarray(a)
print(a_numpyarray[0:11]) #[10.5]
Remove print from the last line. Just keep this :
compute_opening_duration('5:30:00', '16:00:00')

Check Date Format from a Python Tkinter entry widget

Using a Tkinter input box, I ask a user for a date in the format YYYYMMDD.
I would like to check if the date has been entered in the correct format , otherwise raise an error box. The following function checks for an integer but just need some help on the next step i.e the date format.
def retrieve_inputBoxes():
startdate = self.e1.get() # gets the startdate value from input box
enddate = self.e2.get() # gets the enddate value from input box
if startdate.isdigit() and enddate.isdigit():
pass
else:
tkinter.messagebox.showerror('Error Message', 'Integer Please!')
return
The easiest way would probably be to employ regex. However, YYYYMMDD is apparently an uncommon format and the regex I found was complicated. Here's an example of a regex for matching the format YYYY-MM-DD:
import re
text = input('Input a date (YYYY-MM-DD): ')
pattern = r'(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])'
match = re.search(pattern, text)
if match:
print(match.group())
else:
print('Wrong format')
This regex will work for the twentieth and twentyfirst centuries and will not care how many days are in each month, just that the maximum is 31.
Probably you've already solved this, but if anyone is facing the same issue you can also convert the data retrieved from the entry widgets to datetime format using the strptime method, and using a try statement to catch exceptions, like:
from datetime import *
def retrieve_inputBoxes():
try:
startdate = datetime.strptime(self.e1.get(), '%Y-%m-%d')
enddate = datetime.strptime(self.e2.get(), '%Y-%m-%d')
except:
print('Wrong datetime format, must be YYYY-MM-DD')
else:
print('startdate: {}, enddate: {}').format(startdate, enddate)
Note that the output string that will result will be something like YYYY-MM-DD HH:MM:SS.ssssss which you can truncate as follows the get only the date:
startdate = str(startdate)[0:10] #This truncates the string to the first 10 digits
enddate = str(enddate)[0:10]
In my opinion, this method is better than the Regex method since this method also detects if the user tries to input an invalid value like 2019-04-31, or situations in which leap years are involved (i.e. 2019-02-29 = Invalid, 2020-02-29 = Valid).

Sort by datetime in python3

Looking for help on how to sort a python3 dictonary by a datetime object (as shown below, a value in the dictionary) using the timestamp below.
datetime: "2018-05-08T14:06:54-04:00"
Any help would be appreciated, spent a bit of time on this and know that to create the object I can do:
format = "%Y-%m-%dT%H:%M:%S"
# Make strptime obj from string minus the crap at the end
strpTime = datetime.datetime.strptime(ts[:-6], format)
# Create string of the pieces I want from obj
convertedTime = strpTime.strftime("%B %d %Y, %-I:%m %p")
But I'm unsure how to go about comparing that to the other values where it accounts for both day and time correctly, and cleanly.
Again, any nudges in the right direction would be greatly appreciated!
Thanks ahead of time.
Datetime instances support the usual ordering operators (< etc), so you should order in the datetime domain directly, not with strings.
Use a callable to convert your strings to timezone-aware datetime instances:
from datetime import datetime
def key(s):
fmt = "%Y-%m-%dT%H:%M:%S%z"
s = ''.join(s.rsplit(':', 1)) # remove colon from offset
return datetime.strptime(s, fmt)
This key func can be used to correctly sort values:
>>> data = {'s1': "2018-05-08T14:06:54-04:00", 's2': "2018-05-08T14:05:54-04:00"}
>>> sorted(data.values(), key=key)
['2018-05-08T14:05:54-04:00', '2018-05-08T14:06:54-04:00']
>>> sorted(data.items(), key=lambda item: key(item[1]))
[('s2', '2018-05-08T14:05:54-04:00'), ('s1', '2018-05-08T14:06:54-04:00')]

Change default dateparcer output

I found dateparser as a great way to change natural language into dates. Now, I am trying to manipulate the output of the parser without success.
from dateparser import parse
import datetime
def pars():
n = "in two days"
x = parse(n, settings={'TIMEZONE': 'US/Eastern'})
print (x)
>>> 2016-08-25 00:18:03.268506
t = datetime.datetime(x)
t.strftime('%m/%d/%Y')
print (t)
pars()
I get the error: TypeError: an integer is required (got type datetime.datetime)
Many things are wrong with the code.
dateparser returns datetime.datetime objects not some ints that is what datetime.datetime expects
strftime does not update the datetime.datetime object in place, if you want to keep the string value it produces, assign it to some var.
def pars():
x = parse('in two days')
t = x.strftime('%m/%d/%Y')
print 'datetime', x
print 'strftime', t
>>> pars()
datetime 2016-09-30 23:34:07.863881
strftime 09/30/2016

Passing parameters to strftime method

I'm new to python. my question is how to pass parameter to date.strftime() or a workaround
Below is the code
from datetime import date
dl_date = date.today()
p = '%d%b%Y' # the format may vary %d%B%Y or %d%m%Y or % d%M%Y etc
file_date_format = "{0}/{1}/{2}".format(str(dl_date.strftime('%r')),str(dl_date.strftime('%r').upper())
, str(dl_date.strftime('%r'))) % (p[:2], p[2:4], p[4:6])
print(file_date_format)
Help is much appreciated.
No need to use percent style string formatting here. Just stick the p slices directly in the strftime calls.
from datetime import date
dl_date = date.today()
p = '%d%b%Y' # the format may vary %d%B%Y or %d%m%Y or % d%M%Y etc
file_date_format = "{0}/{1}/{2}".format(
str(dl_date.strftime(p[:2])),
str(dl_date.strftime(p[2:4]).upper()),
str(dl_date.strftime(p[4:6]))
)
print(file_date_format)
Result:
14/NOV/2014

Resources