Date Parsing problem while Integrating to Oracle PMS - python

I'm recieving date in PMS message something like this |GA090616|GD090617|
which means Guest Arrival is at 09-06-16 and Guest Deprature is at 09-06-17
I wanted to parse it as date using python.
I've also visited stack oveflow[1, 2 ...] for this but as solution I've found
from datetime import datetime
self.DATE_FROMAT='%d/%m/%y'
arrival_date=datetime.strptime('90616', self.DATE_FROMAT).date()
print(arrival_date)
and it's not possible to parse it like this due to its unclear format.
I'm not sure if 09 is a month or a date, but from what I've seen in documents and PDFs, it appears to be a month.
Is there any better solution for this kind of date parsing? or suggestions for my expectations.
09-06-16,
09-06-17
Note:
Please Just take the date from the string 090617 and parse it as a date. That will be helpful.

You can do this with regex matching, you can either split the string with msg.split("|") or not, but that depends on your use case.
import re
from datetime import datetime
msg = "GA090616|GD090617|"
DATE_FORMAT='%d%m%y'
ar = re.match("GA(\d{6})", msg)
dp = re.match("GD(\d{6})", msg)
guest_arrival = datetime.strptime(ar.group(1), DATE_FORMAT).date()
guest_departure = datetime.strptime(dp.group(1), DATE_FORMAT).date()
Although not fully tested, this should be a boilerplate as to how to retrieve the date from the message. Remember to remove the \ from the date format, as that is not included in the message.

Related

Can I iterate through a whole CSV checking only one column

I know the main question is simple sounding, but I am specifically trying to iterate a whole CSV to find a certain variable while maintaining all the other columns connected to it. I am trying to create a file that essentially checks a certain date and then emails reminders or other templates to a list of students that qualify (based on the date or course) for the reminders. Currently with my code, I can't figure a way to keep the variables linked. I can get a list of students that I want to email, but am having trouble with the names staying linked to the emails I want.
import pandas as pd
import datetime as dt
from datetime import timedelta
import os
from email.message import EmailMessage
df = pd.read_excel('Students.xlsx')
EMAIL_ADDRESS = os.environ.get('EMAIL_USER')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASS')
MAIL_LIST = ''
STUDENT_MAIL = df.student_email
DUE_DATE = df.course_completion_date
COURSE = df.course_section
START_DATE = dt.date.today()
END_DATE = START_DATE + timedelta(days=6)
I then have my codes for basic templates which I have tested and used prior so I know work.
But then I have tried several loops to try and add student emails to it through a loop so for example I would want all students finishing within a week to receive an email
for date in DUE_DATE:
if START_DATE <= date <= END_DATE:
MAIL_LIST = MAIL_LIST + STUDENT_EMAIL
else:
Now I know this looks dumb but this was just my last attempt at trying to get it to work. But I have tried several other ways to get it to work but the problem I run into is that the for loop has to be a single column to make a list it can check against but I need it connected to the second column of their emails to make the mailing list. Am I overcomplicating this I feel like I'm kind of going crazy
Using the DataFrame already will keep the variables linked like you would for index in rows and columns.
If you are trying to just grab the row matching the email you can use .loc to find the matching row for students to emails.
something like:
df.loc[x]['MAIL_LIST']
pandas.DataFrame.loc

Converting free-text user replies to datetimes

I am trying to figure out a clever way to take a user's input and store it in a database to be retrieved at a later date.
For context, this is a Discord bot where I am trying to track users' schedules. The idea is that the user could say "&addtime 12/30/1 12pm CST" and the bot would record that they will be online at 12/30/1/ at 12pm CST
The reason I want to track the timezone is so I can convert all the timezones to a specific timezone so that timezones wont get confused.
So after someone adds their time above, if I (someone PST), goes to retrieve when people will be online, I can type "&schedules PST" and get all of the times in the specified timezone.
The problem I'm facing now is all of the datetime examples I can find online all take very exact and specific input. I'm looking for a more forgiving function that is smart enough to figure out datetimes.
Figured it out with this method. it only supports US timezones, but that was enough for my needs:
from dateutil import parser
from dateutil import tz
import pytz
def parse_date(self, msg):
ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')
us_tzinfos = {'CST': CT, 'CDT': CT,
'EST': ET, 'EDT': ET,
'MST': MT, 'MDT': MT,
'PST': PT, 'PDT': PT}
usertime = parser.parse(msg, tzinfos=us_tzinfos)
servertime = usertime.astimezone(pytz.timezone("America/Phoenix"))
parse_date("12/30/20 12pm EST")

Best practices to filter in Django

In one of the pages of my Django app I have a page that simply displays all employees information in a table:
Like so:
First Name: Last Name: Age: Hire Date:
Bob Johnson 21 03/19/2011
Fred Jackson 50 12/01/1999
Now, I prompt the user for 2 dates and I want to know if an employee was hired between those 2 dates.
For HTTP GET I just render the page and for HTTP POST I'm sending a URL with the variables in the URL.
my urls.py file has these patterns:
('^employees/employees_by_date/$','project.reports.filter_by_date'),
('^employees/employees_by_date/sort/(?P<begin_date>\d+)/(? P<end_date>\d+)/$', EmployeesByDate.as_view()),
And my filter_by_date function looks like this:
def filter_by_date(request):
if request.method == 'GET':
return render(request,"../templates/reports/employees_by_date.html",{'form':BasicPrompt(),})
else:
form = BasicPrompt(request.POST)
if form.is_valid():
begin_date = form.cleaned_data['begin_date']
end_date = form.cleaned_data['end_date']
return HttpResponseRedirect('../reports/employees_by_date/sort/'+str(begin_date)+'/'+str(end_date)+'/')
The code works fine, the problem is I'm new to web dev and this doesn't feel like I'm accomplishing this in the right way. I want to use best practices so can anyone either confirm I am or guide me in the proper way to filter by dates?
Thanks!
You're right, it's a bit awkward to query your API in that way. If you need to add the employee name and something else to the filter, you will end up with a very long URL and it won't be flexible.
Your filter parameters (start and end date) should be added as a query in the url and not be part of path.
In this case, the url would be employees/employees_by_date/?start_date=xxx&end_date=yyy and the dates can be retrieved in the view using start_date = request.GET['start_date].
If a form is used with method='get', the input in the form are automatically converted to a query and appended at the end of the url.
If no form is used, parameters need to be encoded with a function to be able to pass values with special characters like \/ $%.
Use Unix timestamps instead of mm/dd/yyyy dates. A unix timestamp is the number of seconds that have elapsed from Jan 1 1970. ("The Epoch".) So it's just a simple integer number. As I'm writing this, the Unix time is 1432071354.
They aren't very human-readable, but Unix timestamps are unambiguous, concise, and can be filtered for with the simple regex [\d]+.
You'll see lots of APIs around the web use them, for example Facebook. Scroll down to "time based pagination", those numbers are Unix timestamps.
The problem with mm/dd/yyyy dates is ambiguity. Is it mm/dd/yyyy (US)? or dd/mm/yyyy (elsewhere)? What about mm-dd-yyyy?

Formating Django Datetime objects outside template

I love the date tag that comes with Django.
Exceptionally, I'd like to format a DateTime object in my view (because I need to send a formated date string to an API, and not to display it in a Django template).
Do you know if there is a way to use this Django "system" outside templates?
In the mean time, I tried to use the strftime Python method but found out some con's:
It does not use the same format chars as Django, which makes my code deals with 2 different ways to handle date formatting.
By default, it doesn't care about the Django locales and writes English dates.
Thanks :)
The template tag is built on the Django formats utility libraries. See django.utils.formats.date_format for a named date format or django.utils.formats.dateformat.format for arbitrary ones. For example:
from datetime import datetime
# Date format string
from django.utils.formats import dateformat
formatted_date = dateformat.format(datetime.now(), "r")
# Named format
from django.utils.formats import date_format
formatted_date = date_format(datetime.now(), "SHORT_DATE_FORMAT")

Making Django queries with localized dates

In my form I have a DateField called booking_date that is rendered with the AdminDateWidget. The contents of the booking_date field needs to be internationalized. The problem appears when I want to use the value of the field in something like this:
booking = Booking.objects.get(booking_number='BN34D', booking_date='2010-11-21')
But if my date format is '%d.%m.%Y':
booking = Booking.objects.get(booking_number='BN34D', booking_date='21.11.2010')
I get a 'ValidationError: Enter a valid date in YYYY-MM-DD format'
How can I make the query regardless of the date format used?
You should parse it first with a localized version of the strftime format.
from datetime import datetime
d = datetime.strptime('...')
booking.objects.get(..., booking_date=d.date())
Use these formats in strptime:
http://linux.die.net/man/3/strftime
You shouldn't rely on passing directly from the user into the query.
Looks like you should be doing the following from your specific example:
d = datetime.strptime('%d.%m.%Y')
booking = Booking.objects.get(booking_nmber='BN34D', booking_date=d)
As I understand your question, you don't know for sure in advance, which locale will be used. That can bring you into unsolvable problems. ("10-11-12" could be Oct 11, 2012 or Nov 12, 2010 or ...)
So you must have a limited, distinguishable set of possible formats. Then you can do:
POSSIBLE_FORMATS = ('%d.%m.%Y', '%Y-%m-%d', '...')
for f in POSSIBLE_FORMATS:
try:
d = datetime.date.strptime(date_str, f)
break
except ValueError:
continue
raise ValueError
booking = Booking.objects.get(booking_number='BN34D', booking_date=d)
I have solved the problem using this:
from django.utils import formats
formats.get_format('DATE_INPUT_FORMATS')[0]
This format is then used for parsing the date like xyld showed.

Categories

Resources