Calculate Field to remove time from datetime Python - 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", "")

Related

cannot convert null to strftime in django

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()])

OperationFailure Unsupported projection option: endingDate

I am trying to get the document whose endingDate is greater or equal to currentDateTime and also fetching entityID.
{"_id":{"$oid":"5ecfba0b1191f2b87ee1ccd2"},
"entityId":"5ecfb9d9d654557162afd861",
"endingDate":{"$date":"2020-08-11T00:00:00.000Z"}
My query is:
cursor= list(db.collection.find({},{"entityId":1,
"endingDate":{"$gte":datetime.datetime.now().isoformat()}}))
But it giving me error.
OperationFailure: Unsupported projection option: endingDate: { $gte: "2020-08-11T19:28:06.677643" }
Edit 1:
I tried this query also
import datetime
from datetime import datetime
temp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
date_time_obj = datetime.strptime(temp, '%Y-%m-%d %H:%M:%S')
cursor=list(db.TrendAnalysisSystem_jobdata.find({},
{"entityId":1,"hashTags":1,"skillsRequired":1,
"specialization":1,"endingDate":{"$gte":date_time_obj}}))
still getting the same error
You put the find condition into the projection argument. Try:
cursor= list(db.collection.find({"endingDate": {"$gte":datetime.datetime.now().isoformat()}},{"entityId":1, }))

Translate a date in the python source in django

How can I translate a date in my views.py? If I try to translate it with gettext it returns me this error: an integer is required (got type str).
For translating a date i mean for example from english version (May 30, 2019) to italian one (30 Maggio 2019). I've to return the date in a json response. This is my code:
from django.utils.translation import gettext as _
...
#AutoLanguage #It's a middleware that enables i18n
date = datetime.date.today()
date_translated = _(date)
return JsonResponse({'date': date_translated})
Use locale.setlocale in your view:
import locale
def view_name(request):
QUERY_RESULT = MODEL_NAME.objects.get(pk=event_id) #ANY QUERY
try:
locale.setlocale(locale.LC_TIME, 'fr_FR.utf8') #your language encoding
except:
locale.setlocale(locale.LC_TIME, 'fr_FR')
translated_date = QUERY_RESULT.DATE.strftime("%A %d %B %Y") #<= format you want
You'll find the strftime formats in the datetime doc
for me it gives translated_date = "mardi 11 juin 2019"

How to calculate the number of days remaining for another date

How to import a date from view and calculate the number of days remaining for another date?
Here is the solution I tried but it's not working:
class saisir_soumi(osv.osv):
_name='saisir.soumi'
def compa_date(self,cr,uid,ids,args,fields,context=None):
r = {}
date_format = "%D/%M/%Y"
joining_date = 'date_depot'
current_date = '29/04/2016 02:02:02'# current date
d1 = datetime.strptime(joining_date, date_format)
d2 = datetime.strptime(current_date, date_format)
diff = current_date - datetime.date.today()
return diff.days
_rec_name = 'NumOffre'
_columns = {
'NumOffre' : fields.char('N° Offre',required=True),
'organisme_s' : fields.char('Organisme',required=True),
'date_depot' : fields.datetime('Date dépot de soumission'), # the date to be seized and used for its difference with current date( today)
'jrestant': fields.function(compa_date,string='Jours restant')
}
_sql_constraints = [
('uniq_NumOffre', 'unique(NumOffre,id)', "numero offre doit resté unique !"),
]
you have to do it properly:
specify correct date/time format
parse datetime from string
substract the same data types: datetime - datetime
Code:
In [68]: current_date = '29/04/2016 02:02:02'
In [69]: date_format = '%d/%m/%Y %H:%M:%S'
In [70]: (datetime.datetime.strptime(current_date, date_format) - datetime.datetime.now()).days
Out[70]: 5

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

Categories

Resources