Dziugito Bizox
Dziugito Bizox

Reputation: 55

Python: Django comparing timezone.now() with DateTimeField Object

I'm trying to validate if the date isn't earlier than the current time. So I've read somewhere in the forums that I should use timezone.now() instead of datetime.now()

Django is giving you a timezone-aware datetime object. datetime.now() is giving you a timezone-naive datetime object. You can't compare these.

Instead use django.utils.timezone.now(), which provides the type of datetime

So basically as a Django developer, I should better use what Django can offer in default. I got these settings in the main settings file:

TIME_ZONE = 'Europe/Vilnius'

USE_I18N = True

USE_L10N = True

USE_TZ = True

This is my logic for validating the provided date/time:

if date <= timezone.now():
    raise serializers.ValidationError("Meeting could not start earlier than the current time")
return date

But it always returns the date object instead of raising the ValidationError. These are the times which I'm playing with:

if timezone.now() < parse(reservation['date_from']):
    raise serializers.ValidationError("Meeting could not start earlier than the current time")

!NOTE: I'm using .parse() to convert the object from str to datetime object.

timezone.now() returns - 2020-11-22 00:16:55.334792+00:00
reservation['date_from'] returns - 2020-12-04T16:32:00+02:00 
reservation['date_from'] returns - 2020-12-04 16:32:00+02:00

Upvotes: 0

Views: 2111

Answers (2)

datosula
datosula

Reputation: 1586

To make sure you're comparing dates in same timezones you'd better convert them to same timezone. Actually I prefer converting to UTC. As you're using .parse() (I assume from dateutil) the resulting datetime value (including timezone, offset etc.) depends on the string it was presented. So, you may convert the resulting datetime into UTC using .astimezone(pytz.utc). And as django.utils.timezone.now() returns current time in UTC you may compare them directly. For more info you may print the result of parse(reservation['date_from']).astimezone(pytz.utc) to see actual time in UTC.

So I'd offer using comparison in this way:

if timezone.now() < parse(reservation['date_from']).astimezone(pytz.utc):
    raise serializers.ValidationError("Meeting could not start earlier than the current time")

Upvotes: 3

Lars
Lars

Reputation: 1270

Use this in Models.py for setting date automatically :-

date_time = models.DateTimeField(auto_now_add=True)

Upvotes: -1

Related Questions