Django Auth user date_joined field datetime to string - python

When i am fetching the stored datetime value from auth user in django the value comes as below is there a way to convert this into normal date time format may be like "dd:mm:yyyy hh:mm:ss" or some string value that can be displayed in better(other) format
date_joined = request.user.date_joined
#date_joined value is
#datetime.datetime(2016, 9, 11, 16, 6, 22, 314637, tzinfo=<UTC>)

You can format a datetime object using its strftime() method, for example like this:
date_joined = request.user.date_joined
date_joined.strftime("%d:%m:%y %H:M:S")
If you want to display a datetime object in Django template, you can use the builtin date filter.
{{ date_joined|date:"d:m:Y H:i:s")

Related

How to pass date string to datetime field in django?

I need the number (as integer) of users that signed up (User.date_joined) between '2016-01-01'(string) and '2016-04-01' (string) (both dates fully included)
The below queries didn't give me accurate results, since the date_joined is datetime field
User.objects.filter(date_joined__gte='2016-01-01',date_joined_lte='2016-04-01').count()
User.objects.filter(date_joined__range('2016-01-01 00:00:00','2016-04-01 12:59:59')).count()
I am new to django and python , want to know how to pass the string date values to datetime field and use of range function
dt1 = datetime.datetime(2016, 1, 1) # midnight
dt2 = dt1 + datetime.timedelta(days=1)
User.objects.filter(date_joined__range=(dt1, dt2)).count()

Django ORM Syntax for 'LIKE' queries with respect to Datetime

I have this table which has column "date" in the format "2021-03-12 08:12:44.350176".
I want to compare a external date such as "2021-03-12 08:12:44"
I have tried this
new_date = datetime.datetime(2021, 3, 12, 8, 12, 44, tzinfo=<UTC>)
obj = Test.objects.filter(date__contains=new_date).all()
But it doesn't work, it returns empty sets.
My goal is to fetch all the records against the new_date.
Is there a way to remove milliseconds or way to compare the two dates?
It seems you want to compare datetimes upto the second while truncating the milliseconds. You can do that (and similar) by using either Trunc [Django docs] or one of it's subclasses. For truncating to the seconds you can use TruncSecond for your purpose:
import datetime
from django.db.models.functions import TruncSecond
from django.utils import timezone
new_date = datetime.datetime(2021, 3, 12, 8, 12, 44, tzinfo=timezone.utc)
obj = Test.objects.annotate(
trunc_date=TruncSecond(
'date',
tzinfo=timezone.utc
)
).filter(trunc_date=new_date)
according to [Django Docs]:
date
For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value.
date means a datetime.date object.
so you can use __date for datetime fields.

Django 1.11 - convert a datetime string with timezone 2018-01-01T00:00:00+03:00 into datetime object to be used for queryset

I am using Django 1.11 and Postgres 9.4.
How can I convert this
2018-01-01T00:00:00+03:00
into a datetime object that can be used for queryset like below
Tracking.objects.filter(created_at__gte=input_datetime)
for Z time I can use this:
input_datetime = datetime.datetime.strptime("2019-11-01T01:36:56.233032Z", "%Y-%m-%dT%H:%M:%SZ")
but how can I make it work for this time (which seems to have timezone).
I tried this but it didnt work.
input_datetime = datetime.datetime.strptime('2018-01-01T00:00:00+03:00','%Y-%m-%dT%H:%M:%S.%f%z')
Here is my model.py
class Tracking(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
You can actually use Pythons standard datetime lib for this. Somethid like this:
from datetime import datetime
a = '2018-01-01T00:00:10+03:00'
datetime.datetime(2018, 1, 1, 0, 0, 10, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800)))
It will give you a datetime.datetime object which you can use for watever later on.
With the standarddatetime module this should work:
datetime.strptime('2018-01-01T00:00:00+03:00', '%Y-%m-%dT%H:%M:%S%z')
With the Django's timezone module, the closest match format that I got is this:
timezone.datetime.strptime('2018-01-01T00:00:00+0300', '%Y-%m-%dT%H:%M:%S%z')
This example doesn't include : in the offset part 2018-01-01T00:00:00+0300.

create a datetime instance of a particular format

By default when we create a datetime instance, the format includes microseconds.
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2017, 6, 19, 16, 13, 7, 415321)
If I don't want the microseconds part in the instance then I do this,
>>> str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
>>> new_dt = datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
So my question here is that is there any way where we can specify the format in which we want the datetime instance to be created rather than converting it to formatted string we want and then converting back to datetime instance.
A datetime object has no format. It is not created in any specific format, it is just an instance of a class. That instance has attributes, and those attributes have values.
If you need to have an instance that represents a time with the microsecond attribute set to 0, just use the datetime.replace() method to create a new instance from one with all the other attributes correct:
now = datetime.now()
now_without_ms = now.replace(microsecond=0)
However, if you wanted to format a datetime object for printing, then just format it without the microseconds component:
print(now.strftime('%Y-%m-%d %H:%M:%S'))
You don't have to use the microsecond attribute anywhere.

Timezone not working properly in Django

I want to change timezone in Django, so I read documentation how to do it nad here's what I've got:
#settings.py
TIME_ZONE = 'Europe/Ljubljana'
#models.py #date_time gets filled with "auto_now=True")
date_time = models.DateTimeField(auto_now=True)
UTC DST offset for given location (Europe/Ljubljana) is +2, while in my db I see timestamp of UTC. So what am I missing?
Or is this working as intended so it gets processed for each request separately (useful for people in different timezones)? But if this is the case, what's the use of setting TIME_ZONE = 'Europe/Ljubljana'?
From the documentation
When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.
so the datetime in your DB will always be stored in UTC, but will be displayed using the correct TZ in templates and forms.
To get the date in correct TZ elsewhere, use astimezone():
>>> from myapp.models import Details
>>> import pytz
>>> d = Details.objects.get(pk=1)
>>> d.added
datetime.datetime(2016, 5, 28, 18, 59, 55, 841193, tzinfo=<UTC>)
>>> localdate = d.added.astimezone(pytz.timezone('Europe/Ljubljana'))
>>> localdate
datetime.datetime(2016, 5, 28, 20, 59, 55, 841193, tzinfo=<DstTzInfo 'Europe/Ljubljana' CEST+2:00:00 DST>)

Categories