cannot convert null to strftime in django - python

I'm trying to convert the time in 12 hours format where I have few rows with time as NULL. I'm passing it as dictionary. How could I leave that NULL rows and convert others rows with have time
Here, what I have tried
views.py
def GetUserInProgress(userid):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetUserInProgress] #UserId=%s', (userid,))
result_set = cursor.fetchall()
data =[]
for i in range(len(result_set)):
data.append({
'TaskId':result_set[i][0],
'CreatedOn':result_set[i][13],
'CreatedBy':result_set[i][14],
'StartedOn':result_set[i][15],
'ClosedOn':result_set[i][16],
'Requester':result_set[i][17],
'StartedOnPST':result_set[i][31],
'ClosedOnPST':result_set[i][32],
'ClosedonPST_Final':result_set[i][33].strftime('%d-%m-%Y %I:%M %p'),
})
return Response(data)

'ClosedonPST_Final':result_set[i][33].strftime('%d-%m-%Y %I:%M %p') if result_set[i][33] else None
you can do a check

Not tested, but it should work:
def GetUserInProgress(userid):
def _emptyIfNull(v):
return v.strftime('%d-%m-%Y %I:%M %p') if v else ""
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetUserInProgress] #UserId=%s', (userid,))
return Response([{
'TaskId':result_set[i][0],
'CreatedOn': _emptyIfNull(result_set[i][13]),
'CreatedBy': _emptyIfNull(result_set[i][14]),
'StartedOn': _emptyIfNull(result_set[i][15]),
'ClosedOn': _emptyIfNull(result_set[i][16]),
'Requester': _emptyIfNull(result_set[i][17]),
'StartedOnPST': _emptyIfNull(result_set[i][31]),
'ClosedOnPST': _emptyIfNull(result_set[i][32]),
'ClosedonPST_Final': _emptyIfNullresult_set[i][33],
} for i in cursor.fetchall()])

Related

Why is my date in python wrong after formating using timedelta?

I am using Django and have a problem with a date that I need to calculate.
The Variable data > test should be 17:00 and not 15:00. Why does this happen as soon as I format the date?
My timezone is Europe/Berlin. Changing the timezone has to effect to the time printing in test. It is always -2h
def date(req):
now = timezone.now()
model = MyModel.objects.filter(date__gt=now).first()
next = model.date
future = timezone.timedelta(hours=float(model.future)) #model.future = 1.5
open = next-future
date = next.strftime('%Y/%m/%d')
data = {
'next': next,
'date': date,
'time': open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f'),
'test': open.strftime('%Y/%m/%d %H:%M:%S%z')
}
What I get:
next: 20. November 2021 18:30
date: 2021/11/20
time: 2021-11-20 15:15:00.000000
test: 2021/11/20 15:00:00+0000
https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/#naive-and-aware-datetime-objects
You should use:
from django.utils import timezone
now = timezone.now()
Datetime isn't time-zone aware.
You cut the timezone info (the offset +02:00) with .strftime(). You need to include it with %z.
In case you want to convert it to a time string with the offset already added.
open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
This works for me.
from django.utils import timezone
def date(req):
now = timezone.now()
model = MyModel.objects.filter(date__gt=now).first()
next = model.date
future = timezone.timedelta(hours=float(model.future)) #model.future = 1.5
open = next-future
date = timezone.localtime(open)
data = {
'next': date.strftime('%Y/%m/%d %H:%M:%S'),
'date': date.strftime('%Y/%m/%d'),
'time': date.strftime('%H:%M:%S'),
}

How to validate if two dates are the same?

How do I implement functionality where a user can only update an entry when the date_created and date_modified fields of the diary entry are the same?
This is what I have implemented. I have compared the date_created field of the entry model in the db to datetime.date.today().
Data model
class DiaryEntry():
def __init__(self):
self.title = ''
self.body = ''
self.date_modified = None
self.date_created = datetime.date.today()
def save(self, current_user_email):
# insert data into db
query = "INSERT INTO entries (owner_id, title, body, date_created, date_modified) \
VALUES ((SELECT user_id from users where email ='{}'), '{}', '{}', '{}','{}')" \
. format(current_user_email,
self.title,
self.body,
self.date_created,
self.date_modified
)
db.execute(query)
Method
def update_diary_entry(self,entry_id):
query = "select * from entries where entry_id='{}'".format(entry_id)
result = db.execute(query)
entry = result.fetchone()
data = request.get_json()
date_created = entry[4]
if date_created == datetime.date.today():
query = "update entries set title='{}',body='{}' where entry_id='{}'"\
.format(data['title'], data['body'], int(entry_id))
db.execute(query)
return {'message': 'diary entry updated succesfully','date':date_created}, 406
else:
return {'message': 'diary entry can only be updated on the day it was created'}, 406
I am currently getting the second return statement. What could I be doing wrong?
It looks like you have date_created as a string (str) within update_diary_entry(). That will cause an invalid comparison to a Python datetime.date object unless you parse the string into the same type:
>>> import datetime
>>> date_created = '2018-07-29'
>>> date_created == datetime.date.today()
False
>>> datetime.datetime.strptime(date_created, '%Y-%m-%d').date() == datetime.date.today()
True
The classmethod strptime() parses a string that looks like a date into a datetime.datetime object. You need to then grab just the date component from this to enable the comparison that you want. If you have a differently-formatted date-string, see strftime() and strptime() Behavior.

Django 1.6 format datetime in views

I've a booking form in my template that sends an email when it's submitted. In my database the datetime field is shown like: Oct. 6, 2015, 3:58 p.m. But when I get the email the datetime field is shown like: 2015-10-06 15:58:50.954102 How do i format it such that in the email it's shown exactly like how it's shown in the database?
models.py
class Booking(models.Model):
patient_name = models.CharField(max_length=1300)
phone = models.IntegerField(null=True, blank = True)
preference = models.CharField(max_length=150,null = True, blank = True) #morning,noon,night
doctor = models.ForeignKey(Doctor)
clinic = models.ForeignKey(Clinic,null=True, blank = True)
datetime = models.DateTimeField(auto_now=True, auto_now_add=True, blank = True, null = True)
def __unicode__(self):
return u"%s %s" % (self.patient_name, self.doctor)
views.py
lead = Booking(doctor_id=doctor.id, clinic_id=doctor.clinic.id, preference=preference, patient_name=patient_name, phone=phone)
lead.save()
body = "Request Made: " + str(lead.datetime) +" "
email = EmailMessage('Blah', body, to=[clinic.email])
email.send()
You can format datestrings using strftime
>>> from datetime import date
>>> dt = date(2015, 10, 6, 15, 58, 50)
>>> dt.strftime("%b. %-d %Y %-I:%M %p")
'Oct. 6 2015 2:12 PM'
There's a list of the codes for strftime at at http://strftime.org/
So in your view you would do something like
body = "Request Made: %s " % lead.datetime.strftime("%b. %-d %Y %-I:%M %p")
Thats not exactly how it's in the database, it's just what the tool you use to view inside the database, displays datetime.
However if you want your datetime to look exactly like that, use:
lead.datetime.strftime("%b. %-d %Y %-I:%M %p")
Here are some relevant sources:
https://docs.python.org/2/library/datetime.html#datetime.datetime
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Calculate Field to remove time from datetime Python

I want to calculate the value of a new field by grabbing the date only (strip out the time) from the existing field DATE_VAL.
I keep getting errors however. Here is my code.
formatter_string = "%m%d%y"
arcpy.CalculateField_management("joined", "Date", dt.strftime("!DATE_VAL!", formatter_string), "PYTHON_9.3", "")
If I try the following:
arcpy.CalculateField_management("joined", "Date", "dt.strftime(!DATE_VAL!, formatter_string).date()", "PYTHON_9.3", "")
I get the following error:
ExecuteError: ERROR 000539: Error running expression: dt.strftime(u"5/1/2014 3:00:00 AM", formatter_string).date()
When I try the following:
formatter_string = "%m/%d/%Y %I:%M:%S %p"
arcpy.CalculateField_management("joined", "Date",
dt.strptime("!DATE_VAL!", formatter_string).date(), "PYTHON_9.3", "")
I get the error: ValueError: time data '!DATE_VAL!' does not match format '%m/%d/%Y %I:%M:%S %p'
datetime.datetime objects have a date method that will return a datetime.date object.
formatter_string = "%m/%d/%Y %I:%M:%S %p"
arcpy.CalculateField_management("joined", "Date",
"dt.strptime(!DATE_VAL!, formatter_string).date()", "PYTHON_9.3", "")
I found some code to use update cursor rather than the calculate field. This seems to work for my purpose. I probably should have posted this in the gis stack exchange. sorry.
arcpy.AddField_management("joined", "Date", "DATE")
rows = arcpy.UpdateCursor("joined")
for row in rows:
datetimeVal = row.getValue("DATE_VAL")
formattedTime = dt.strftime(datetimeVal, "%m/%d/%Y")
row.setValue("Date", formattedTime)
rows.updateRow(row)
del rows, row
Im not the arcpy guy but this should do:
Instead of:
arcpy.CalculateField_management("joined", "Date", "dt.strftime(!DATE_VAL!, formatter_string).date()", "PYTHON_9.3", "")
Do this:
date_format = '%m/%d/%Y'
formatter_string = '%m/%d/%Y %I:%M:%S %p'
arcpy.CalculateField_management("joined", "Date", "dt.strftime(!DATE_VAL!, formatter_string).date().strftime(date_format)", "PYTHON_9.3", "")

How to convert string date in datetime.date format

I want to convert date like Jun 28 in datetime format like 2014-06-28. I tried following code and many more variation which gives me correct output in ipython but I m unable to save the record in database. It throws error as value has an invalid date format. It must be in YYYY-MM-DD format. Can anyone help me to fix this issue ?
Following is the code snippet
m = "Jun"
d = 28
y = datetime.datetime.now().year
m = strptime(m,'%b').tm_mon
if m > datetime.datetime.now().month:
y=y-1
new_date = str(d)+" "+str(m)+" "+str(y)
new_date = datetime.datetime.strptime(new_date, '%b %d %Y').date()
my models.py is as
class Profile(models.Model):
Name = models.CharField(max_length = 256, null = True, blank = True)
Location = models.CharField(max_length = 256, null = True, blank = True)
Degree = models.CharField(max_length = 256, null = True, blank = True)
Updated_on = models.DateField(null = True, blank = True)
Code that saves to model is like
def save_record(self):
try:
record = Profile(Name= indeed.name,
Location = loc,
Degree = degree,
Updated_on = new_date,
)
record.save()
print "Record added"
except Exception as err:
print "Record not added ",err
pass
Thanks in advance
Once you have a date object, you can use the strftime() function to format it into a string.
Let's say new_date is your date object from your question. Then you can do:
new_date.strftime('%Y-%m-%d')
Btw, you can do the same with a datetime object too.
EDIT:
Double check whether your Updated_on field uses DateField or DateTimeField. That will affect whether you use a datetime.date() object or datetime.datetime() object, respectively.
I tried on console:
>>import datetime
>>datetime.datetime.strptime("Jun-08-2013", '%b-%d-%Y').date()
datetime.date(2013, 6, 8)
There are several errors in the code. So solution should be:
m = "Jun"
d = 28
if datetime.datetime.strptime("Aug",'%b').month > datetime.datetime.now().month:
y= (datetime.datetime.now() - relativedelta(years=1)).year #from dateutil.relativedelta import relativedelta
else:
y=datetime.datetime.now().year
new_date = str(m)+"-"+str(d)+"-"+str(y)
new_date = datetime.datetime.strptime(new_date, '%b-%d-%Y').date()
new_date is a date object, so it should be saved to models.DateField() without any problem(including format issues).

Categories

Resources