A
A
Alexander2017-09-27 18:55:27
Django
Alexander, 2017-09-27 18:55:27

How to add string date to current date?

from django.utils.timezone import now

print(now(), obj.freeze_time, sep="|||")
# вывод: 2017-09-27 15:26:40.445545+00:00|||1:58:29

I try to add them,
now() + obj.freeze_time
I get an error:
unsupported operand type(s) for +: 'datetime.datetime' and 'str'

Tried different methods. Perhaps not correctly approached the solution of the problem.
There is a model (Advertising):
class General(models.Model):
    ...
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

    freeze = models.BooleanField(default=False)
    freeze_time = models.CharField(max_length=200, null=True, blank=True)

The user in the admin panel will indicate the start date of the ad ( start_date ), and the end date of the ad ( end_date ). It can also freeze ads.
Algorithm  : The freeze_time
field will store the remaining time of the ad. If the user freezes the ad , then we take the end_date and subtract the current date from it now() and put this value in the freeze_time field . If the user unfreezes the ad , we take the current date now() in the field and add freeze_time to it and put this value in the end_date field

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Kuzmichev, 2017-09-27
@kentuck1213

Use the freeze_timenumber of seconds for storage, it will be more convenient to store in the database and it is conveniently converted to / from timedelta , which can already be added to datetime.
Example:

>>> from datetime import datetime, timedelta, now
>>> begin_date = datetime(2017, 9, 1, 0, 0, 0)
>>> end_date = datetime(2017, 9, 30, 0, 0, 0)
>>> freeze_time = end_date - now()
>>> freeze_time
datetime.timedelta(2, 17264, 411894)
>>> freeze_time.total_seconds()
190064.411894
>>> freeze_time = int(freeze_time.total_seconds())
>>> freeze_time
190064
>>> now() + timedelta(seconds=freeze_time)
datetime.datetime(2017, 9, 30, 0, 1, 1, 371159)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question