0

Here I am using Django 3.0 and Python 3.7

Here I am getting time from django template and i need to combine this time and today date as save it in database as DateTimeField

Here is my models.py

class WorkTime(models.Model):
    client = models.ForeignKey(Client,on_delete=models.CASCADE)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    total_time = models.TimeField(blank=True, null=True)

Here is my views.py

class AddWorkTimeView(View):
    def get(self, request):
        client = request.user.client
        return render(request,'core/work_time_form.django.html')


    def post(self, request):
        c = request.user.client
        start_time = request.POST.get('start_time')   # print start_time - 11:15     
        end_time = request.POST.get('end_time') # print end_time - 14:15

        WorkTime.objects.create(client=c,start_time=start_time,end_time=end_time)
        return redirect('work_times')

Here is my work_time_form.django.html

<form class="form-horizontal" method="post">
        {% csrf_token %}
        <div class="row">
            <div class="span10 offset1">
                
                    <div class="control-group">
                        <label class="control-label pull-left">Start Time</label>
                        <input type="time" step="900" class="input_box" name="start_time">
                    </div>
                   
                    <div class="control-group">
                        <label class="control-label pull-left">End Time</label>
                        <input type="time" step="900" class="input_box" name="end_time">
                    </div>
                    <div id="form-buttons-container" class="form-actions">
                        <div class="controls">
                            <input type="submit" class="btn btn-inverse" value="Save">
                        </div>
                    </div>
                    
                
            </div>
        </div>
    </form> 
   

Here what format i want it to save to my datebase

Example:  2020-11-03 10:30:00 (here date is today date)

And also calculate the time difference between start_time and end_time in minutes and save it to total_time field

To achieve this what changes i need to do to my code

Please help me to solve this issue

Harika
  • 1
  • 2
  • 1
    Does this answer your question? [Easiest way to combine date and time strings to single datetime object using Python](https://stackoverflow.com/questions/9578906/easiest-way-to-combine-date-and-time-strings-to-single-datetime-object-using-pyt) – Abdul Aziz Barkat Nov 03 '22 at 07:12
  • I got it it worked for me now how can i calculate the time difference between start_time and end_time into minutes and Save it total_time field – Harika Nov 03 '22 at 07:55
  • You have the start time and the end time saved... Why would you want to save their difference to the DB as well when that can simply be calculated from the 2 values? As for how to calculate the difference maybe some [research](https://www.google.com/search?q=Python+difference+between+2+datetime) before asking would be useful? – Abdul Aziz Barkat Nov 03 '22 at 07:59

2 Answers2

0

Use datetime.strftime and datetime.combine for it. For your code :

class AddWorkTimeView(View):
    def get(self, request):
        client = request.user.client
        return render(request,'core/work_time_form.django.html')


    def post(self, request):
        c = request.user.client

        today = datetime.datetime.today().date()
        start_time = request.POST.get('start_time')   # print start_time - 11:15    
 
        start_time = datetime.datetime.strptime(start_time, "%H:%M").time()
        start_time = datetime.datetime.combine(today, start_time)

        end_time = request.POST.get('end_time') # print end_time - 14:15

        end_time = datetime.datetime.strptime(end_time, "%H:%M").time()
        end_time = datetime.datetime.combine(today, end_time)

        WorkTime.objects.create(client=c,start_time=start_time,end_time=end_time)
        return redirect('work_times')

Also don't forget to import datetime module as :

import datetime
ilyasbbu
  • 1,468
  • 4
  • 11
  • 22
  • I got it it worked for me now how can i calculate the time difference between start_time and end_time into minutes and Save it total_time field – Harika Nov 03 '22 at 07:55
0

Here I tried...

views.py

def WorktimeView(request):
    if request.method == 'POST':
        st_time = request.POST.get('start_time')
        ed_time = request.POST.get('end_time')
        p =datetime.strptime(st_time,'%H:%M')
        q =datetime.strptime(ed_time,'%H:%M')
        st_time_stamp = datetime.now().replace(hour=p.hour,minute=p.minute,second=0)
        ed_time_stamp = datetime.now().replace(hour=q.hour,minute=q.minute,second=0)
        WorkTime(
            client=request.user,
            start_time = str(st_time_stamp),
            end_time = str(ed_time_stamp),
            total_time = str(ed_time_stamp-st_time_stamp)
            
        ).save()
        

    return render(request, 'index.html',)

Html code

{% block body %}

<form class="form-horizontal" method="post">
     {% csrf_token %}
     <div class="row">
          <div class="span10 offset1">

               <div class="control-group">
                    <label class="control-label pull-left">Start Time</label>
                    <input type="time" step="900" class="input_box" name="start_time">
               </div>

               <div class="control-group">
                    <label class="control-label pull-left">End Time</label>
                    <input type="time" step="900" class="input_box" name="end_time">
               </div>
               <div id="form-buttons-container" class="form-actions">
                    <div class="controls">
                         <input type="submit" class="btn btn-inverse" value="Save">
                    </div>
               </div>
          </div>
     </div>
</form>
{% endblock body %}

admin.py

@admin.register(WorkTime)
class WorkTimeAdmin(admin.ModelAdmin):
    list_display = ("hours_display", "end_time", "start_time", "client",)[::-1]

models.py

class WorkTime(models.Model):
    client = models.ForeignKey(User,on_delete=models.CASCADE)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    total_time = models.CharField(max_length=8,default='00:00:00')

    @property
    def hours_display(self):
        return(f"{self.total_time} hours")

Html Form

enter image description here

Output (admin panel)

enter image description here