How to compare datatime in python? - python-2.7

Goal:I need to find the difference between the start_time and current_time and see if its greater then an hour .
start_time = 2016-08-15 23:52:51
current_time = 2016-08-17 13:42:12
How do that in python ?
Thanks

You have to use Datetime and timedelta
>>> from datetime import datetime
>>> delta = datetime(2016,8,15,23,52,51) - datetime(2016,8,17,13,42,12)
>>> delta
datetime.timedelta(-2, 36639)
>>> delta.seconds
36639

Related

how to convert a datetime format to a millisec in python 2?

so python2 does not have datetime.timestamp() is there any way to convert a simple datetime format to epoch like format in other words in milliseconds , or is there any other way to convert the start_date to milliseconds format
from datetime import datetime
import dateparser
time_interval = "1h"
start_date = dateparser.parse(time.interval)
print (str(start_date))
date_in_millisec = start_date.timestamp()
from datetime import datetime
import dateparser
time_interval = "1h"
start_date = dateparser.parse(time.interval)
print (str(start_date))
date_in_millisec_compared_to_now = datetime.now() - start_date
print (str(date_in_millisec_compared_to_now))

Django: Convert string to datetime object

Here is the datetime string:
dt = '2016-04-07 23:00:00'
I have tried datetime.strptime(year+"-"+day+"-"+month+" "+hour+":"+mins+":"+"00", '%Y-%d-%m %H:%M:%S') but I get this error:
type object 'datetime.datetime' has no attribute 'datetime'
from dateutil import parser
date_string = '2016-04-07 23:00:00'
date_object = parser.parse(date_string)
change
from datetime import datetime
to
import datetime
and try this. hope this helps..
import datetime
datetime.datetime.strptime(dt, "%Y-%m-%d %H:%M:%S")

How to create a Django custom Field to store MYSQL DATETIME(6) and enable fractional seconds (milliseconds and or microseconds) in Django/MySQL?

MySQL 5.6.4 and up expands fractional seconds support for TIME, DATETIME, and TIMESTAMP values, with up to microseconds (6 digits) precision: http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
Django 1.5 and up supports fractional seconds as imputformat: https://docs.djangoproject.com/en/1.5/ref/settings/#datetime-input-formats
But the DATETIME(6) field isn't implemented in Django yet.
https://code.djangoproject.com/ticket/19716
I decided to write a custom DateTimeFractionField. It's the standard DateTimeField with the DATETIME([1-6]) db_type. 'precicion' is to set milliseconds, microseconds or any other fraction precicion.
class DateTimeFractionField(models.DateTimeField):
description = "Datetimefield with fraction second."
def __init__(self, precision, *args, **kwargs):
self.precision = precision
super(DateTimeFractionField, self).__init__(*args, **kwargs)
def db_type(self, connection):
return 'DATETIME(%s)' % self.precision
class MyModel(models.Model):
dt_micros = DateTimeFractionField(6)
dt_millis = DateTimeFractionField(3)
dt = models.DateTimeField()
def __unicode__(self):
return "%s - %s" %(self.dt_micros, self.dt_millis)
The mysql backend is responsible for replacing milliseconds with 0. The Django documentation suggests to write my own backend. https://docs.djangoproject.com/en/1.5/ref/settings/#engine
I hacked:
$ cd /path/to/site-packages/django/db/backends/
$ cp -r mysql mysql564
And modified mysql564/base.py:
Line 42:45
from django.db.backends.mysql564.client import DatabaseClient
from django.db.backends.mysql564.creation import DatabaseCreation
from django.db.backends.mysql564.introspection import DatabaseIntrospection
from django.db.backends.mysql564.validation import DatabaseValidation
Line 167
supports_microsecond_precision = True
Line 214
compiler_module = "django.db.backends.mysql564.compiler"
Line 357
return six.text_type(value) #value.replace(microsecond=0)
Line 368
return six.text_type(value) #value.replace(microsecond=0)
Line 373
return [first, second] #return [first.replace(microsecond=0), second.replace(microsecond=0)]
Then i activated my new backend in settings.py:
'ENGINE': 'django.db.backends.mysql564',
When I add and save my model in the admin, the values get saved to de db! :)
But they are not returned (None - None and empty form fields). :(
What am I missing here?
Why are DateTimeFractionField values not returned?
Is there a better (simpler) way to implement a datetimefield that support fractions?
I know there are other db's supporting fractions. But I like to use MySQL and get the ticket a little closer to fixed.
UPDATE:
It's not (only) the form, getting a datetime object from de db fails.
In [1]: from spacetime.models import MyModel
In [2]: from django.shortcuts import get_object_or_404
In [3]: get_object_or_404(MyModel, pk=1).dt
Out[3]: datetime.datetime(2013, 7, 25, 0, 22, 23)
In [4]: get_object_or_404(MyModel, pk=1).dt_millis
In [5]: get_object_or_404(MyModel, pk=1).dt_millis.__class__
Out[5]: NoneType #This should be datetime.datetime
I've tried this succesfully, but my approach is quite different:
I split the info in a DateTimeField (UTC) and a IntegerField (microseconds = uS):
from datetime import datetime, timedelta
import pytz
class MyModel (models.Model):
# My model stuff and other fields here
_UTC = models.DateTimeField ()
_uS = models.IntegerField()
And then I set a property in the class to return UTC with microseconds and zone info aware (because my database doesn't support zoneinfo)
#property
def UTC (self):
utc = self._UTC
us = self._uS
# add microseconds
utc += timedelta(microseconds=us)
return utc.replace(tzinfo=pytz.utc)
#UTC.setter
def UTC (self,utc):
self._UTC = utc-timedelta(microseconds=utc.microsecond) # without microseconds
self._uS = utc.microsecond

Django DateTimeField()

In Django: I have a date and time that I need to enter into my database model, which has a column models.DateTimeField(). It seems that no matter what I do, I get a ValidationError: enter a valid date/time format.
I have a string like this:
myStr = "2011-10-01 15:26"
I want to do:
p = mytable(myDate = WHAT_GOES_HERE)
p.save()
Please don't point me to a duplicate question. I have looked around and they point to other questions which again point to questions, which point to some documentaton, which just doesn't get me what I need. Thanks!
>>> import datetime
>>> myStr = "2011-10-01 15:26"
>>> WHAT_GOES_HERE = datetime.datetime.strptime(myStr, "%Y-%m-%d %H:%M")
>>> WHAT_GOES_HERE
datetime.datetime(2011, 10, 1, 15, 26)
>>>
datetime.strptime()
From the Django documentation:
# inserting datetime.now()
import django.utils.timezone as tz
mytable.objects.create(myDate=tz.localtime())
# inserting any date:
import pytz
import django.utils.timezone as tz
from datetime import datetime as dt
my_tz = pytz.timezone('Europe/Bucharest')
my_date = dt(2018, 8, 20, 0)
mytable.objects.create(myDate=tz.make_aware(my_date, my_tz))
You can simply do the following
myStr = '2011/10/01 15:26'
And then when creating your object just use myStr as an attribute value:
p = mytable(myDate = myStr)
p.save()

Django, actual month in queryset

how ill, get my register based in the current (actual) month in my queryset?, i have a ModelManager(), that just show the LIVE register status, but now i want to show the register with LIVE status and in the current (actual) month, i know that ill make something like .filter(...), but i dont know how get the current month..
model.py
#manager
class LiveNoticiaManager(models.Manager):
def get_query_set(self):
return super(LiveNoticiaManager,self).get_query_set().filter(status=self.model.LIVE_STATUS)
thanks guys.
http://docs.djangoproject.com/en/dev/ref/models/querysets/#month
You can
>>> import datetime
>>> today = datetime.date.today()
>>> MyModel.objects.filter(mydatefield__year=today.year,
mydatefield__month=today.month)
That's if you are only interested in gettting the month:
import datetime
today = datetime.date.today()
months = ['zero','January','February','March','April','May','June','July','August','September','October','November','December']
current_month = months[today.month]