Answer the question
In order to leave comments, you need to log in
How to correctly compare the date and time received from a database field in Django?
I'm trying to write a function that will check whether the next hour has come since the record was created. those.
if the entry was created at 12:43 and checked at 13:05 the function should return true if not false.
the main problem lies in not understanding what type of data is stored in the property of the ar object, a string or a Datetime object, the
timestamp is added automatically by specifying auto_now = True
timestamp = models.DateTimeField(auto_now=True)
ar = Article.objects.get(pk=1)
ar.timestamp = ???
Answer the question
In order to leave comments, you need to log in
https://docs.python.org/3/library/datetime.html
Use the datetime.strptime method to convert a string to a datetime object, where you can set any string parsing format.
Once you've done that, you can do whatever you want with this object, such as extracting the hour.
import datetime
string = "2020-09-04T13:24:22.717154Z"
string_as_date = datetime.datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%fZ')
string_as_date
# Out: datetime.datetime(2020, 9, 4, 13, 24, 22, 717154)
string_as_date.hour
# Out: 13
from dateutil import parser
string = "2020-09-04T13:24:22.717154Z"
string_as_date = parser.isoparse(string)
string_as_date.hour
# Out: 13
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question