Search code examples
pythonpytz

pytz timezone DST issue


I'm passing two naive dates to a form. Then using pytz to ensure the timezones are set as EST. However, it results in an error. I'm guessing this is due to the DST issue. Dates and DST are confusing. Can someone enlighten me as to how to make the "DST proof"?

from rest_framework import serializers
from datetime import datetime
import pytz


class SearchForm(serializers.Serializer):
    start_date = serializers.DateField(required=True)
    end_date = serializers.DateField(required=False)

    def save(self):
        # Doesn't actually save, 
        start_date = self.validated_data['start_date']
        end_date = self.validated_data['end_date']

        # Convert dates to EST timezone
        est = pytz.timezone('America/New_York')
        start_date = datetime.combine(start_date, time.min).astimezone(est)
        end_date = datetime.combine(end_date, time.max).astimezone(est)

        print(f'Start date: {start_date} => {start_date.tzinfo}')
        print(f'End date: {end_date} => {end_date.tzinfo}')

        assert start_date.tzinfo == end_date.tzinfo

        # Filter based on timeframe
        qs = self.filter_timeframe(qs, start_date, end_date)

        return SearchSerializer(qs, many=True)

Passing a the start_date as "2018-11-1" and end_date as "2018-11-5" results in an AssertionError. Printing out the dates results in:

Start date: 2018-11-01 00:00:00-04:00 => America/New_York
End date: 2018-11-05 23:59:59.999999-05:00 => America/New_York

The question is why is the end_date timezone -05:00 and not -04:00 like start_date?


Solution

  • America/New_York is not the same as EST. The former adjusts for the daylight saving shifts. The latter is fixed to be Eastern Standard Time. Use:

    est = pytz.timezone('EST')