Django: Convert string to datetime object - django

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")

Related

RuntimeWarning: DateTimeField received a naive datetime, with correct timezone and settings

I am receiving this error message:
RuntimeWarning: DateTimeField Z.data_zal received a naive datetime
(2020-11-05 07:13:24) while time zone support is active.
warnings.warn("DateTimeField %s received a naive datetime (%s)"
At this step of creating my models instance: views.py
from django.utils import timezone
t = Z(data_z=timezone.now().strftime('%Y-%m-%d %H:%M:%S'), data_r=data_r, author=request.user)
try:
t.save()
So as far as I know this error occurs when using datetime module instead of timezone.
Sometimes the problem lies in wrong settings.py but I am running:
TIME_ZONE = 'Europe/Warsaw'
USE_TZ = True
What seems to be the issue?
Don't .strftime() you make timezone.now() naive.
https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/

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))

Utilising Django annotations with F fields to serialize properties

I have the following model property:
#property
def is_complete(self):
return datetime.datetime.now() >= datetime.datetime.combine(self.date, self.ending_time)
I was wondering, how could I convert this to an annotation, such that:
MyObject.objects.annotate(is_complete=?).filter(is_complete=True)
Would be equiavalent and valid?
You could use ExpressionWrapper to combine the date and time, convert the result to python actual datetime object and finally you can make the comparison.
from django.db.models import DateTimeField, ExpressionWrapper, F
from django.utils import timezone
MyCustomObject.objects.annotate(combine_datetime=ExpressionWrapper(F('date') + F('ending_time'), output_field=DateTimeField())).filter(combine_datetime__lte=timezone.now())
Docs: Django 2.2 Query Expression F with anotation
Try this :
from django.db.models.expressions import Value
from django.db.models.functions.datetime import TruncDate
MyObject.objects.annotate(is_complete=Value(datetime.datetime.now() >= datetime.datetime.combine(TruncDate('date'),TruncDate('ending_time'))))).filter(is_complete=True)

'None type' object has no attribute 'year'

I'm trying to get the year from a datetime form but I'm getting this error when I run the project code 'None type' object has no attribute 'year' I've tried both import datetime and from datetime import datetime but with no success. Although in another function placed before this one in the same file views.py I wrote the same code (of year getting...) and it works very well!
PS: when I run the code on the ipdb shell it works correctly!
this the code:
from datetime import datetime
def My_function(request):
data = tableA.find()
dt = datetime.now()
y = dt.year
m = dt.month
d = dt.day
for i in data:
if i['ma_date'].year == y:
ma_liste.append([i["ma_date"])
return render(request, ma_page.html, ma_liste)
and this is the erreor
**AttributeError at /ma_page/
'NoneType' object has no attribute 'year'**
This has nothing to do with datetime. Your data item has no year attribute.
You haven't shown your code or a structure for this object, but it's likely it's just a multidimensional array, in which case you could use: i['ma_date']['year'].

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()