user1094786
user1094786

Reputation: 6800

Parsing a Datetime String into a Django DateTimeField

I have a Django app with a model that contains a field of type DateTimeField.
I am pulling data from the web in the format of 2008-04-10 11:47:58-05.
I believe that the last 3 characters in this example are the timezone.
How can I preserve that data in the DateTimeField, and is there an easy conversion between the two? Setting the DateTimeField to simply contain a string of the above format throws a ValidationError.

Thank you!

Upvotes: 53

Views: 71392

Answers (6)

reza_khalafi
reza_khalafi

Reputation: 6544

To make standard format:

from django.utils.dateparse import parse_datetime
formatted_datetime = parse_datetime(YOUR_STRING_DATETIME).strftime('%Y-%m-%d %H:%M:%S')
print(f"formatted_datetime: {formatted_datetime}")

You will see something like this:

2022-02-09 12:58:52

Be successful

Upvotes: 3

RameshD
RameshD

Reputation: 962

String format of Django DateTimeField is "%Y-%m-%dT%H:%M:%S.%fZ". Hence, conversion between eachother can be done using strptime() or strptime() using this format.

eg. for string formatted value (2016-10-03T19:00:00.999Z), it can be converted to Django datetime object as :

from datetime import datetime

datetime_str = '2016-10-03T19:00:00.999Z'

datetime_object = datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%S.%fZ")

Upvotes: 7

user1600649
user1600649

Reputation:

You can also use Django's implementation. I would in fact prefer it and only use something else, if Django's parser cannot handle the format.

For example:

>>> from django.utils.dateparse import parse_datetime
>>> parse_datetime('2016-10-03T19:00:00')
datetime.datetime(2016, 10, 3, 19, 0)
>>> parse_datetime('2016-10-03T19:00:00+0200')
datetime.datetime(2016, 10, 3, 19, 0, tzinfo=<django.utils.timezone.FixedOffset object at 0x8072546d8>)

To have it converted to the right timezone when none is known, use make_aware from django.utils.timezone.

So ultimately, your parser utility would be:

from django.utils.dateparse import parse_datetime
from django.utils.timezone import is_aware, make_aware

def get_aware_datetime(date_str):
    ret = parse_datetime(date_str)
    if not is_aware(ret):
        ret = make_aware(ret)
    return ret

Upvotes: 110

Paul Tomblin
Paul Tomblin

Reputation: 182782

I've been using this:

from django.utils.timezone import get_current_timezone
from datetime import datetime
tz = get_current_timezone()
dt = tz.localize(datetime.strptime(str_date, '%m/%d/%Y'))

Upvotes: 18

nisc
nisc

Reputation: 4400

You can use

import dateutil.parser
dateutil.parser.parse('2008-04-10 11:47:58-05')

Which returns a datetime (that can be assigned to the DateTimeField).

Upvotes: 61

RyanWilcox
RyanWilcox

Reputation: 13972

If you're using Django Forms, you can specify input_formats to your DateField. See the DateField documentation

If you are wanting to parse arbitrary date information, you could use something like parsedatetime and implement a method that Django calls to do the parsing before it hits the validators. (See this SO answer for a good summary of how validations work and when to insert them)

Upvotes: 3

Related Questions