Looking up relative dates from Django DateTimeField - python

model:
class MyClass(models.Model):
car = models.ForeignKey(Car)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
sql:
SELECT car FROM cars_myclass WHERE date < NOW() - INTERVAL 1 DAY;
So, I have something like:
cars = MyClass.objects.all().filter(date < ... )
But how to write NOW() - INTERVAL 1 DAY ? Thanks.

Pass datetime.datetime object (substracted by datetime.timedelta object):
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 12, 29, 21, 54, 30, 836000)
>>> now - datetime.timedelta(days=1)
datetime.datetime(2013, 12, 28, 21, 54, 30, 836000)
import datetime
cars = MyClass.objects.filter(date__lt=datetime.datetime.now() - datetime.timedelta(days=1))
UPDATE Comment by Mikko Ohtamaa:
Also to avoid problems with timezones I recommend using timezone.now() instead of datetime.datetime.now() (available since Django 1.4)
import datetime
from django.utils import timezone
cars = MyClass.objects.filter(date__lt=timezone.now() - datetime.timedelta(days=1))

Related

How to extract day, month and year from utcnow?

I have the following var: time_created = datetime.utcnow()
How to create a time_created_day var from time_created that will contain only Y, M, d
like this datetime.datetime(2017, 11, 7)
I have the following solution:
from datetime import date
time_created_day = date(time_created.year, time_created.month, time_created. day)
is it the best way?
Use datetime.utcnow().date()
datetime.utcnow().date()
datetime.date(2017, 11, 7)
Adding to answer
The datetime object always contains year, month, day as well as hours, minutes, seconds, and microseconds. It is a combination of what the date and time objects contain, see datetime Objects
from datetime import datetime
# this is your datetime object
time_created = datetime.utcnow()
# when you want to see it formatted as Y,M,D call the date method
date_created = time_created.date()
time_created
date_created
Output:
datetime.datetime(2017, 11, 7, 23, 43, 43, 761750)
datetime.date(2017, 11, 7)`
Use time_created.day to find the day.
time_created_day = time_created.day
(Similar for month and year)
here it is easiest for you
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + " " + month + " " + day;

How do i get the next day datetime in isoformate

I'm using the Google Calendar API.
I've read the quickstart
> eventsResult = service.events().list(
calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
orderBy='startTime').execute()
But I tried to add a timeMax parameter to filter the event i got.
I wish to get the event from now to the end of today.
I start at:
> import datetime
now = datetime.datetime.now()
then I got:
AttributeError: module 'datetime' has no attribute 'now'
I read that most coder is confused by the datetime.datetime.
I propose to use the module time instead. With the function localtime with no argument passed you can generate a timestamp with the accuracy of a second.
Example
>>> import time
>>> ts = time.localtime()
>>> print ts
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=9, tm_hour=12, tm_min=39, tm_sec=50, tm_wday=2, tm_yday=221, tm_isdst=0)
>>> print ts.tm_year, ts.tm_mon, ts.tm_mday
2017 8 9
>>> print ts[3:6]
(12, 39, 50)
As you see, you have several methods to extract the information from the timestamp.
[EDIT]
If the ISO-Format of the timestamp is important, ignore my answer... ;)
>>> import datetime as dt
>>> from datetime import date,timedelta
>>> dt.datetime.today() - timedelta(days=-1)
#datetime.datetime(2017, 8, 10, 18, 16, 29, 785131)
>>> Td = dt.datetime.today() - timedelta(days=-1)
>>> Td
#datetime.datetime(2017, 8, 10, 18, 16, 41, 786500)
>>> Td = Td.isoformat()
>>> Td
#'2017-08-10T18:16:41.786500'
>
I finally solved this problem with datetime.
import datetime
now = datetime.datetime.now()
night = now.replace(hour=23, minute=59)
#I'm at UTC+8
utcNow = now-datetime.timedelta(hours=8)
utcnight = night - datetime.timedelta(hours=8)
print (utcNow.isoformat() + 'Z')
print(utcnight.isoformat() + 'Z')
2017-08-10T02:48:16.413384Z
2017-08-10T15:59:16.413384Z
for my local time it is:
2017-08-10 10:48:16.413384Z
2017-08-10 23:59:16.413384Z

How to calculate diff between two dates in django

I want to calculate days difference between current date and previous date.
i am trying this code
requiremntObj = CustomerLeads.objects.all()
a = datetime.datetime.now().date()
for i in requiremntObj:
date1=i.posting_date
diff = a-date1
print diff
I got a error unsupported operand type(s) for -: 'datetime.date' and 'unicode'
For current date i am getting datetime object and for date1 i am getting unicode.
posting_date = models.DateField()
If you have DateTimeField you can use:
delta = datetime.now().date() - posting_date
print delta.days
If it is string, then you have to convert:
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime(str(datetime.now().date()), date_format)
b = datetime.strptime(str(posting_date), date_format)
delta = b - a
print delta.days
Here is post.
This code for HTML in Django
<p> {{ to_date|timeuntil:from_date }} </p>
This code for server site in python
import datetime
from_date = datetime.datetime(2019, 10, 21)
to_date = datetime.datetime(2019, 10, 25)
result = to_date - from_date
print(result.days)

Convert GMT based time to UTC python

I get a date like 2014/08/19 03:38:46 GMT-4 from the database.
How do I convert this into UTC formatted date in Python?
PS: I use Python 2.6.6
Having a non-naive datetime object, you only should invoke astimezone method with desired timezone
>>> import pytz
>>> from dateutil import parser
# dateutil.parser get a datetime object from string, we ensure that is a non-naive datetime
>>> parser.parse('2014/08/19 03:38:46 GMT-4')
datetime.datetime(2014, 8, 19, 3, 38, 46, tzinfo=tzoffset(None, 14400))
>>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
>>> dt.astimezone (pytz.utc)
datetime.datetime(2014, 8, 18, 23, 38, 46, tzinfo=<UTC>)
You are right in your comment, utc time should go behind, so while I think another solution, what about this
>>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
>>> dt.replace(tzinfo=pytz.utc) + dt.tzinfo._offset
datetime.datetime(2014, 8, 19, 7, 38, 46, tzinfo=<UTC>)
GMT-4 is ambiguous: is it time in America/New_Your (-0400 utc offset) or in Europe/Moscow (+0400)?
$ TZ=GMT-4 date +%Z%z
GMT+0400
$ TZ=UTC-4 date +%Z%z
UTC+0400
$ TZ=America/New_York date +%Z%z
EDT-0400
$ TZ=Europe/Moscow date +%Z%z
MSK+0400
Your comment suggests that you need the sign of the utc offset reversed.
Python 2.6 has no fixed-offset timezones in stdlib. You could use the example implementation from the datetime docs:
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
class FixedOffset(tzinfo):
"""Fixed UTC offset: `local = utc + offset`."""
def __init__(self, offset, name):
self.__offset = timedelta(hours=offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
utc = FixedOffset(0, "UTC")
Then to parse the time string, you could use strptime():
dt = datetime.strptime("2014/08/19 03:38:46 GMT-4", "%Y/%m/%d %H:%M:%S GMT-4")
aware = dt.replace(tzinfo=FixedOffset(-4, "GMT-4"))
print(aware) # -> 2014-08-19 03:38:46-04:00
print(aware.astimezone(utc)) # -> 2014-08-19 07:38:46+00:00

Get tz offset from string

I have a date which is in local time:
date: "2013-12-02 22:00:00"
and another value the tz:
timezone_offset: "GMT-0800"
If I : dateutil.parser.parse(date).isoformat() I will get:
"2013-12-02T22:00:00+0000"
I want to implement the date in ISO format with the tz info and get a result of:
"2013-12-02T22:00:00-0800"
Something close to: parse(date,tzinfos=??).isoformat() ? How can I get the tzinfo from the string timezone_offset ?
>>> from dateutil.parser import parse
>>> dt = parse("2013-12-02 22:00:00" + "GMT+0800")
>>> dt.isoformat()
'2013-12-02T22:00:00-08:00'
Note: the sign is reversed.
You could also do it using only stdlib:
>>> from datetime import datetime
>>> dt = datetime.strptime("2013-12-02 22:00:00", "%Y-%m-%d %H:%M:%S")
>>> dt = dt.replace(tzinfo=FixedOffset(-8*60, "GMT+0800"))
>>> dt.isoformat()
'2013-12-02T22:00:00-08:00'
where FixedOffset is taken from datetime docs:
from datetime import tzinfo, timedelta
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return timedelta(0)
Here's the same using pytz module:
>>> from datetime import datetime
>>> import pytz
>>> dt = datetime.strptime("2013-12-02 22:00:00", "%Y-%m-%d %H:%M:%S")
>>> dt = pytz.timezone('Etc/GMT+8').localize(dt)
>>> dt.isoformat()
'2013-12-02T22:00:00-08:00'
Here are two approaches you could use:
>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2013, 11, 12, 9, 10, 48, 404000)
>>> dtutcnow
datetime.datetime(2013, 11, 12, 15, 10, 48, 404000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(-1, 64800)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(-6, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2013-11-12T09:10:48.404000-6:00'
Or this:
>>> import datetime, pytz # 3rd Party
>>> datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
'2013-11-12T09:15:20.688000-0600'
>>>
The main advantage of the second method is it makes your time string 'timezone aware'. From the docs:
There are two kinds of date and time objects: “naive” and “aware”.
This distinction refers to whether the object has any notion of time
zone, daylight saving time, or other kind of algorithmic or political
time adjustment. Whether a naive datetime object represents
Coordinated Universal Time (UTC), local time, or time in some other
timezone is purely up to the program, just like it’s up to the program
whether a particular number represents metres, miles, or mass. Naive
datetime objects are easy to understand and to work with, at the cost
of ignoring some aspects of reality.
Hope this helps!

Categories