1

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)
Axil
  • 3,606
  • 10
  • 62
  • 136
  • Try removing the `.` in your format string: `'%Y-%m-%dT%H:%M:%S%f%z'` – ikkuh Nov 07 '19 at 15:12
  • does not work--> ValueError: time data '2018-01-01T00:00:00+03:00' does not match format '%Y-%m-%dT%H:%M:%S%f%z' .... i did this: input_datetime = datetime.datetime.strptime('2018-01-01T00:00:00+03:00','%Y-%m-%dT%H:%M:%S%f%z') – Axil Nov 07 '19 at 15:14
  • In that case you are using a Python version < 3.7 and also need to remove the last `:` in your `date_string` argument. – ikkuh Nov 07 '19 at 15:22
  • im using Python 3.6.3 – Axil Nov 07 '19 at 15:23

2 Answers2

2

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.

Henry Harutyunyan
  • 2,355
  • 1
  • 16
  • 22
1

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.

Davit Tovmasyan
  • 3,238
  • 2
  • 20
  • 36
  • it works, im trying to understand abit, you mean timezone +0300 is not accounted for ? – Axil Nov 07 '19 at 15:21
  • what is %z for ? isnt that for +0300 ? – Axil Nov 07 '19 at 15:22
  • Docs are missing some examples, Henry's answer proves that %z will catch also +03:00 – Davit Tovmasyan Nov 07 '19 at 15:31
  • didnt work datetime.strptime('2018-01-01T00:00:00+03:00', '%Y-%m-%dT%H:%M:%S%z'). AttributeError: module 'datetime' has no attribute 'strptime' – Axil Nov 07 '19 at 22:43
  • this also didnt work - datetime.datetime.strptime('2018-01-01T00:00:00+03:00', '%Y-%m-%dT%H:%M:%S%z') . ValueError: time data '2018-01-01T00:00:00+03:00' does not match format '%Y-%m-%dT%H:%M:%S%z' – Axil Nov 07 '19 at 22:45