Axil
Axil

Reputation: 3311

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)

Upvotes: 1

Views: 853

Answers (2)

Henry Harutyunyan
Henry Harutyunyan

Reputation: 2415

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.

Upvotes: 2

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

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.

Upvotes: 1

Related Questions