M
M
Maxim2020-09-04 17:02:47
Django
Maxim, 2020-09-04 17:02:47

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 = ???

If you look in the database itself, there is the string "2020-09-04T13:24:22.717154Z"
So the question is:
If a string is stored there, then only regular expressions can be used to get only the hour value? Or are there other better tools?
If there is a Datetime object, then how to get only hours without date and minutes.

From what side to approach this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zexer, 2020-09-04
@maxpointn2point

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

UPD
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 question

Ask a Question

731 491 924 answers to any question